Reflection in C#.Net wtih example

What is reflection

Reflection objects are used for obtaining type information at runtime. Reflection used to dynamically create an instance of a type, bind the type to an existing object, or invoke its methods or access its fields, properties.

System.Reflection namespace, used to provide the classes which used to access to the  metadata of a running program.
 
Uses of Reflection
  • Reflection allows to view metadata at runtime.
  • Reflection allows to examining various types in an assembly and instantiate these types.
  • Reflection allows for late binding to methods and properties.
  • Reflection allows to creating new types at runtime.
1) Load assembly at run time and execute methods using Reflection.
  1. using System.Reflection  
System.Reflection namespace, used to provide the classes which used to access to the  metadata of a running program
  1. Assembly assembly = Assembly.LoadFile(@"C:\Calculation.exe");  
  2. Type Ltype = assembly.GetType("CalcReflection.Calc");  
  3.   
  4. object objCalc = Activator.CreateInstance(Ltype);  
  5.   
  6. MethodInfo method1 = Ltype.GetMethod("AddNumbers");//AddNumbers with int return type  
  7. MethodInfo method2 = Ltype.GetMethod("AddNumber");//AddNumber with void return type  
  8.   
  9.   
  10. int result = (int)method1.Invoke(objCalc, null);  
  11. method2.Invoke(objCalc,null);  
2) Get meta info at run time using reflection
  1. Assembly assembly = Assembly.LoadFile(@"C:\Calculation.exe");    
  2. Type[] type = assembly.GetTypes();  
  3. foreach (Type item in type)  
  4. {  
  5.         Console.WriteLine("\n\nType Name :"+item.Name+"\n");  
  6.         MethodInfo[] method = item.GetMethods();  
  7.         Console.WriteLine("\n************ Method Info ***************\n");  
  8.         foreach (MethodInfo item1 in method)  
  9.         {  
  10.                Console.WriteLine("\nMethod Name :"+item1.Name);  
  11.         }  
  12.         FieldInfo[] field = item.GetFields();  
  13.         Console.WriteLine("\n************ Field Info ***************\n");  
  14.         foreach (FieldInfo item1 in field)  
  15.         {  
  16.                Console.WriteLine("\nField Name :" + item1.Name);  
  17.         }  
  18. }  
That's all. Thanking you. Next time I will come with new topics with example to implement using .Net.