Get the public field with the specified name from a Type in CSharp

Description

The following code shows how to get the public field with the specified name from a Type.

Example


/*from   w  w w .j  a v a 2s.  c  om*/
using System;
using System.Reflection;

public class MyFieldClassA
{
    public string Field = "A Field";
}

public class MyFieldClassB
{
    private string field = "B Field";
    public string Field 
    {
        get
        {
            return field;
        }
        set
        {
            if (field!=value)
            {
                field=value;
            }
        }
    }
}

public class MyFieldInfoClass
{
    public static void Main()
    {
        MyFieldClassB myFieldObjectB = new MyFieldClassB();
        MyFieldClassA myFieldObjectA = new MyFieldClassA();

        Type myTypeA = typeof(MyFieldClassA);
        FieldInfo myFieldInfo = myTypeA.GetField("Field");

        Type myTypeB = typeof(MyFieldClassB);
        FieldInfo myFieldInfo1 = myTypeB.GetField("field", BindingFlags.NonPublic | BindingFlags.Instance);

        Console.WriteLine(myFieldInfo.GetValue(myFieldObjectA));
        Console.WriteLine(myFieldInfo1.GetValue(myFieldObjectB));
    }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    Reflection »




Array
Constructor
Event
Field
Interface
Method
Properties
Type