FieldHandle

In this chapter you will learn:

  1. How to get FieldHandle
  2. Get Field From Field Handle

Get FieldHandle

FieldInfo.FieldHandle Property gets a RuntimeFieldHandle, which is a handle to the internal metadata representation of a field.

using System;//jav a  2s .c om
using System.Reflection;

public class MyClass
{
    public string MyField = "Microsoft";
}

public class FieldInfo_FieldHandle
{
    public static void Main()
    {
        MyClass myClass =new MyClass();
        Type myType = typeof(MyClass);
        try
        {
            FieldInfo myFieldInfo = myType.GetField("MyField", BindingFlags.Public | BindingFlags.Instance);
            if(myFieldInfo!=null)
            {
                RuntimeFieldHandle myFieldHandle=myFieldInfo.FieldHandle;
                DisplayFieldHandle(myFieldHandle);
            }
            else
            {
                Console.WriteLine("The myFieldInfo object is null.");
            }
        }  
        catch(Exception e)
        {
            Console.WriteLine("Exception: {0}", e.Message);
        }
    }

    public static void DisplayFieldHandle(RuntimeFieldHandle myFieldHandle)
    {
        FieldInfo myField = FieldInfo.GetFieldFromHandle(myFieldHandle);      
        Console.WriteLine("The type is {0}.", myField.ToString());
    }
}

Get Field From Field Handle

FieldInfo.GetFieldFromHandle Method gets a FieldInfo for the field represented by the specified handle.

using System;//from  j  a v  a2s.c  om
using System.Reflection;

public class MainClass
{
    public string x;
    public char y;
    public float a;
    public int b;

    public static void Main()
    {
        Type myType = typeof(MainClass);
        FieldInfo [] myFieldInfoArray = myType.GetFields();
        RuntimeFieldHandle myRuntimeFieldHandle;
        for(int i = 0; i < myFieldInfoArray.Length; i++)
        {
            myRuntimeFieldHandle = myFieldInfoArray[i].FieldHandle;
            FieldInfo myFieldInfo = FieldInfo.GetFieldFromHandle(myRuntimeFieldHandle);
            Console.WriteLine("{0}", myFieldInfo);
        }
    }
}

Next chapter...

What you will learn in the next chapter:

  1. How to use reflection to get field value
Home » C# Tutorial » Reflection
Reflection
Type
Type properties
Field reflection
Field Type
Field Attributes
FieldHandle
Field value
Set Field value
delegate reflection
Event reflection
Indexer reflection
Properties Reflection
Method
Parameter
Invoke
Type Instantiating
interface reflection
Generic type reflection
Reflection on nested Types
Subtype
Array reflection
Assembly