Sunday, 26 August 2012

Reflection in C# / MS.NET


Reflection

1        The classes in the System.Reflection namespace, together with System.Type, allows us to obtain information about loaded assemblies and the types defined within them, such as classes, interfaces, and value types.

2        For a given class, using reflection we can query the list of all

a.       Constructors

b.      Methods

c.       Properties

d.      Fields

e.      Events

Note: This information is actually fetched from the Type Metadata and Assembly manifest of an assembly.

 

Following example demonstrates the usage of Reflection API to extract the details as needed.

using System.Reflection

//Sample Class.

class Demo

{

    internal void Bar()

    { }

    public void Foo(int a, string s)

    {

        Console.Write(a + " " + s);

    }

    public int Field1;

    public int Property1

    {

        get

        {

            return Field1;

        }

        set

        {

            Field1 = value;

        }

    }

}

 

static class Program

{

    static void Main()

    {

        Assembly objAssembly = Assembly.Load("mscorlib,2.0.0.0,Neutral,b77a5c561934e089");

        Type[] Types = objAssembly.GetTypes();

 

        // Display all the types contained in the specified assembly.

        foreach (Type objType in Types)

            Console.WriteLine(objType.Name.ToString());

 

        Type tp = typeof(Demo);

 

        //To get the list of all fields of a class.

        foreach (FieldInfo fi in tp.GetFields())

            Console.WriteLine(fi.Name);

 

        //To get the list of all properties of a class.

        foreach (PropertyInfo pi in tp.GetProperties())

            Console.WriteLine(pi.Name);

 

        //To get the list of all methods of a class.

        foreach (MethodInfo mi in tp.GetMethods(BindingFlags.NonPublic))

            Console.WriteLine(mi.Name + " " + mi.GetParameters().Length);

 

        //To create the instance of the class without using “new” operator

        Object ob = Activator.CreateInstance(tp);

 

        //ob.Foo(1, "A"); - Invalid

       

        //Following is equivalent of LateBinding of VB.NET 

        MethodInfo miFoo = tp.GetMethod("Foo");

        object[] arArgs = { 1, "A" };

        miFoo.Invoke(ob, arArgs); //Method Foo is Invoked

    }

}

 

Reflection is ideally used

1.       Building IDE applications like VS.NET

2.       Type browsers

3.       Common code which works on all types.

4.       In serialization, Reflection is used to get all the data of an object which has to be persisted.

 
Thanks for reading this article and I am sure you have understood the same with simple example.

2 comments:

  1. Thanks for Reflection API.
    I understood this.
    I am really learning new things from your blog every week.
    Thanks a lot.

    ReplyDelete
  2. Thnq for Posting,,,,
    Thanks a lot

    ReplyDelete