Get value from a field in CSharp

Description

The following code shows how to get value from a field.

Example


using System;// w  w w.  j  av  a2  s . co m
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 »
    Reflection »




Array
Constructor
Event
Field
Interface
Method
Properties
Type