C# Type GetField(String, BindingFlags)

Description

Type GetField(String, BindingFlags) searches for the specified field, using the specified binding constraints.

Syntax

Type.GetField(String, BindingFlags) has the following syntax.


public abstract FieldInfo GetField(
  string name,
  BindingFlags bindingAttr
)

Parameters

Type.GetField(String, BindingFlags) has the following parameters.

  • name - The string containing the name of the data field to get.
  • bindingAttr - A bitmask comprised of one or more BindingFlags that specify how the search is conducted.
  • bindingAttr - -or-
  • bindingAttr - Zero, to return null.

Returns

Type.GetField(String, BindingFlags) method returns An object representing the field that matches the specified requirements, if found; otherwise, null.

Example

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


using System;//from  ww  w.  j  ava2 s  . c o m
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 »




Array
BitConverter
Boolean
Byte
Char
Console
ConsoleKeyInfo
Convert
DateTime
DateTimeOffset
Decimal
Double
Enum
Environment
Exception
Guid
Int16
Int32
Int64
Math
OperatingSystem
Random
SByte
Single
String
StringComparer
TimeSpan
TimeZone
TimeZoneInfo
Tuple
Tuple
Tuple
Type
UInt16
UInt32
UInt64
Uri
Version