Reflection in .NET Framework

Reflection is the feature in .Net, which enables us to get some information about object in runtime. That information contains data of the class. System.Reflection namespace contains all the Reflection related classes. These classes are used to get information from any of the class under .NET framework.

The Type class is the root of all reflection operations. Type is an abstract base class that acts as means to access metadata though the reflection classes. Using Type object, any information related to methods, implementation details and manipulating information can be obtained. The types include the constructors, methods, fields, properties, and events of a class, along with this the module and the assembly in which these information are present can be accessed and manipulated easily.

public class TestDataType
{
public delegate void DelMaxCounterAttained(int Counter);
public event DelMaxCounterAttained MaxCounterAttained;
public TestDataType()
{
counter = 1;
}
public TestDataType(int c)
{
counter = c;
}
public int counter;
public int Inc()
{
if (counter++ >= 10)
MaxCounterAttained(counter);
return counter;
}
public int Dec()
{
return counter--;
}
}


public class ReflectionSample
{
public static void Main()
{
//At first we should get type of object that was created.
TestDataType testObject = new TestDataType(15);
Type objectType = testObject.GetType();


//Using objectType we can able to extract constructor, method and events information
ConstructorInfo[] info = objectType.GetConstructors();
FieldInfo[] fields = objectType.GetFields();
MethodInfo[] methods = objectType.GetMethods();
EventInfo[] events = objectType.GetEvents();

// get all the constructors
Console.WriteLine("Constructors:");
foreach (ConstructorInfo cf in info)
{
Console.WriteLine(cf);
}
Console.WriteLine();

//get all the fields
Console.WriteLine("Fileds:");
foreach (FieldInfo ff in fields)
{
Console.WriteLine(ff);
}


// get all the methods
Console.WriteLine("Methods and handles:");
foreach (MethodInfo mf in methods)
{
Console.WriteLine(mf);
}

//get all the events
Console.WriteLine("Events:");
foreach (EventInfo ef in events)
{
Console.WriteLine(ef);
}

}
}

Output:

Constructors:
Void .ctor()
Void .ctor(Int32)

Fields:
Int32 counter

Methods and hanles:
void add_MaxCounterAttained(DelMaxCounterAttained)
void remove_MaxCounterAttained(DelMaxCounterAttained)
Int32 Inc()
Int32 Dec()
System.String ToString()
Boolean Equals(System.Object)
Int32 GetHashCode()
System.Type GetType()

Events:
DelMaxCounterAttained MaxCounterAttained

No comments: