Reflection in C#

Reflection is a namespace which provides objects that encapsulate assemblies, modules and types. The objects are of type ‘Type’ (System.Type). With the help of these objects, we can obtain information about the loaded assemblies and the types defined in them (they can be class, struct, interface, methods etc) by accessing their metadata. With the help of reflection you can also create instance of any type dynamically, bind it to any existing object (i.e, late binding), can call its methods, or can access its fields and properties, and attributes etc.

Program prog = new Program();
System.Type t = prog.GetType();

The result will be the <namespace>.<class-name>
Here we are retrieving the type of object ‘prog’. It can also be achieved by using ‘typeof’ -> typeof(Program).

Other example
class Program
{
int number = 10;
static void Main(string[] args)
{
Program prog = new Program();
System.Type t = prog.number.GetType();
Console.WriteLine(t);
Console.ReadKey();
}
}
Output
System.Int32

Note: For using reflection methods make sure you have written : ‘using System.Reflection‘ namespace




How to get information about the methods defined in a class ?

class Program
{
public void sum(int a, int b)
{
Console.WriteLine(a + b);
}
static void Main(string[] args)
{
Program prog = new Program();
System.Type t = prog.GetType(); //returning type of prog
MethodInfo[] info = t.GetMethods();
foreach (MethodInfo item in info)
{
Console.WriteLine(item);
}
Console.ReadKey();
}
}

Here in the above code we have a class ‘Program’ containing a method ‘sum’. Then with the help of ‘GetMethods()’ function we are fetching all the methods available with type t(i.e, the class Program). GetMethods() returns an array of methods of type MethodInfo. You can iterate through this array with foreach.
OUTPUT
Reflection
In the above output window 5 methods are listed. One is sum() with 2 interger type parameters, as it is in our class program. You might be wonder from where the rest 4 methods are coming, so they are defined in the base object class which is the mother of all the classes. plus GetType() from System.Type class.

You can see the list of methods in the intellisense provided by visual studio with help of dot operator. See figure
Reflection

There are a number of methods available, you can get list of constructor – GetConstructors(), or properties – GetProperties() and many more info.

TIP : If you want to build types at runtime, make use of System.Reflection.Emit.

How can you can check if the type is a class ?

By using the ‘IsClass’ property.
System.Type t = prog.GetType();
Console.WriteLine(t.IsClass);

Its return type is boolean hence either True or False will return.

Similar properties are IsInterface, IsGenericType, IsSealed, IsEnum, IsPublic etc.