C# FieldInfo GetValue

Description

FieldInfo GetValue When overridden in a derived class, returns the value of a field supported by a given object.

Syntax

FieldInfo.GetValue has the following syntax.


public abstract Object GetValue(
  Object obj
)

Parameters

FieldInfo.GetValue has the following parameters.

  • obj - The object whose field value will be returned.

Returns

FieldInfo.GetValue method returns An object containing the value of the field reflected by this instance.

Example


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

class MyClass
{
    public static String val = "test";
    public static void Main()
    {
        FieldInfo myf = typeof(MyClass).GetField("val");
        Console.WriteLine(myf.GetValue(null));
        val = "hi";
        Console.WriteLine(myf.GetValue(null));

        MyClass myInstance = new MyClass();
        Type myType = typeof(MyClass);
        FieldInfo[] myFields = myType.GetFields(BindingFlags.Public 
            | BindingFlags.Instance);
        Console.WriteLine(myType);
        for(int i = 0; i < myFields.Length; i++)
        {
            Console.WriteLine("The value of {0} is: {1}",
                myFields[i].Name, myFields[i].GetValue(myInstance));
        }
    }

    public string myFieldA;
    public string myFieldB; 
    public MyClass()
    {
        myFieldA = "A public field";
        myFieldB = "Another public field";
    }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    System.Reflection »




EventInfo
FieldInfo
MemberInfo
MethodInfo
ParameterInfo
TypeInfo