Welcome

Welcome Anonymous

Tuesday, January 25, 2011

.NET Reflection

Reflection is the feature in .Net, which enables us to get some information about object in runtime. That information contains data of the class. Also it can get the names of the methods that are inside the class and constructors of that object.

To write a C# .Net program which uses reflection, the program should use the namespace System.Reflection. To get type of the object, the typeof operator can be used. There is one more method GetType(). This also can be used for retrieving the type information of a class. The Operator typeof allow us to get class name of our object and GetType() method uses to get data about object?s type.

Example program:


namespace Reflection
{
public class TestDataType
{

public TestDataType()
{
counter = 1;
}

public TestDataType(int c)
{
counter = c;
}

private int counter;

public int Inc()
{
return counter++;
}
public int Dec()
{
return counter--;
}

}
public class entry
{
public static void Main(string[] args)
{
TestDataType obj = new TestDataType(15);
System.Type objType = obj.GetType();
ConstructorInfo[] cinfo = objType.GetConstructors();
MethodInfo[] minfo = objType.GetMethods();
Console.WriteLine("Constructors....");
foreach (ConstructorInfo c in cinfo)
{
Console.WriteLine("\t" + c);
}
Console.WriteLine("Methods...");
foreach (MethodInfo m in minfo)
{
Console.WriteLine("\t"+m);
}
Console.Read();
}
}
}