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. This C#
tutorial on reflection explains this feature with a sample class.
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--;
}
}
At first we should get type of object that was created. The following C# .Net
code snippet shows how to do it.
TestDataType testObject = new TestDataType(15);
Type objectType = testObject.GetType();
Now objectType has all the
required information about class TestDataType. We can
check if our class is abstract or if it is a class. The System.Type
contains a few properties to retrieve the type of the class: IsAbstract, IsClass.
These functions return a Boolean value if the object is abstract or of
class type. Also there are some methods that return information about
constructors and methods that belong to the current type (class). It can be
done in a way as it was done in next example:
Type objectType = testObject.GetType();
ConstructorInfo [] info = objectType.GetConstructors();
MethodInfo [] methods = objectType.GetMethods();
// get all the constructors
Console.WriteLine("Constructors:");
foreach( ConstructorInfo cf in info )
{
Console.WriteLine(cf);
}
Console.WriteLine();
// get all the methods
Console.WriteLine("Methods:");
foreach( MethodInfo mf in
methods )
{
Console.WriteLine(mf);
}
Now, the above
program returns a list of methods and constructors of TestDataType
class.
Reflection is
a very powerful feature that any programming language would like to provide,
because it allows us to get some information about objects in runtime. It can
be used in the applications normally but this is provided for doing some
advanced programming. This might be for runtime code generation (It goes
through creating, compilation and execution of source code in runtime).
The Sample
code can be downloaded from here. The attached
example can be compiled using .NET command line csc
command. Type csc Reflection.cs. This will create the executable Reflection.exe,
which can be run as a normal executable.