C# TypeInfo GetField(String)

Description

TypeInfo GetField(String) Searches for the public field with the specified name.

Syntax

TypeInfo.GetField(String) has the following syntax.


public FieldInfo GetField(
  string name
)

Parameters

TypeInfo.GetField(String) has the following parameters.

  • name - The string containing the name of the data field to get.

Returns

TypeInfo.GetField(String) method returns An object representing the public field with the specified name, if found; otherwise, null.

Example

The following example gets the Type object for the specified class, obtains the FieldInfo object for the field, and displays the value of the field.


/*from w w w.  j a va2s .  c  o  m*/
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 »
    System.Reflection »




EventInfo
FieldInfo
MemberInfo
MethodInfo
ParameterInfo
TypeInfo