Reflection is the way of inspecting an assemblies's metadata at runtime. it is used to find all types in an assembly and dynamically invoke methods of an assembly.With the help of reflection you can find what classes, methods, propertied, constructors etc. assembly contains.You can also know what any method is expecting and what will method return and many more.
Uses of reflection :
- When you drag and drop a button on a win form or an asp.net application.the property window uses reflection to show all the properties of the button class so reflection is used by IDE or UI designers .
- When you use ILDASM command to inspect a assembly, internally it's also using reflection..
- Late binding can be achieved by reflection can use reflection to dynamically create an instance of a type, about which we don't have any information at compile time. so reflection enables you to use code that is not available at compile time.
- Suppose you have two alternate implementation of an interface. you want to allow user to pick one or the other using a config file. with reflection, you can simply read the name of the class whose implementation you want to use from config file, and instantiate an instance of that class. this is another example of late binding using reflection.
Following is the example of reflection :
using System.Reflection;
namespace Logicsmaze
{
public class Student
{
public string studenName { get; set; }
public int rollno { get; set; }
public int parentsIncome { get; set; }
public Student()
{
}
public Student(int rollNo,string name,int Income)
{
this.rollno = rollNo;
this.studenName = name;
this.parentsIncome = Income;
}
public static void Scholarship(List<Student>lstStudent)
{
}
}
class Program
{
public static void Main()
{
//Type t = Type.GetType("Logicsmaze.Student"); or
Type t = typeof(Student);
Console.WriteLine("
...............Class Detail..........");
Console.WriteLine(t.Name);
Console.WriteLine(t.FullName);
Console.WriteLine(t.Namespace);
Console.WriteLine();
Console.WriteLine("
...........Properties in Student class........");
PropertyInfo[] properties = t.GetProperties();
foreach (PropertyInfo property in properties)
{
Console.WriteLine(property.Name + " is type of: " + property.PropertyType.Name);
}
Console.WriteLine();
Console.WriteLine("
...........Methods in Student class........");
MethodInfo[] methods = t.GetMethods();
foreach (MethodInfo method in methods)
{
Console.WriteLine(method.Name + " has return type : "+method.ReturnType.Name);
}
Console.WriteLine();
Console.WriteLine("
...........Constructors in Student class........");
ConstructorInfo[] constroctors = t.GetConstructors();
foreach (ConstructorInfo constructor in constroctors)
{
Console.WriteLine(constructor.ToString());
}
Console.Read();
}
}
}
Output :