Knowledge Management Banner

Knowledge Management Banner

C# : Reflection : Part 22

Reflection

  • Relection is used to get meta data of assembly during runtime, or from DLL.
  • It is used to find information like properties, constructors, method
  • With reflection we can dynamically create instance of type(class) and get the existing field or method and can invoke it
  • Refer Following code to understand reflection functioning
 namespace Csharp  
 {  
   class Program  
   {  
     static void Main(string[] args)  
     {  
       //GetType() - gets the type of class  
       Type T = Type.GetType("Csharp.Arithmatic");  
       Console.WriteLine("***********************************");  
       Console.WriteLine("Complete Name : " + T.FullName);  
       Console.WriteLine("Class Name : " + T.Name);  
       Console.WriteLine("Namespace : " + T.Namespace);  
       Console.WriteLine("***********************************");  
       //Print Method  
       Console.WriteLine("Methods in Arithmatic Class");  
       MethodInfo[] methods = T.GetMethods();  
       foreach (MethodInfo method in methods)  
       {  
         //Printing Return Type and Method Name  
         Console.WriteLine(method.ReturnType.Name + " " + method.Name);  
       }  
       Console.WriteLine("***********************************");  
       //Print Properties  
       Console.WriteLine("Properties in Arithmatic Class");  
       PropertyInfo[] properties = T.GetProperties();  
       foreach (PropertyInfo property in properties)  
       {  
         //Printing Property Type and Property Name  
         Console.WriteLine(property.PropertyType.Name + " " + property.Name);  
       }  
       Console.WriteLine("***********************************");  
       //Print Constructors  
       Console.WriteLine("Constructors in Arithmatic Class");  
       ConstructorInfo[] constructors = T.GetConstructors();  
       foreach (ConstructorInfo constructor in constructors)  
       {  
         Console.WriteLine(constructor.ToString());  
       }  
     }  
   }  
   class Arithmatic  
   {  
     public Arithmatic()  
     {  
       NumberOne = 0;  
       NumberTwo = 0;  
     }  
     public int NumberOne { get; set; }  
     public int NumberTwo { get; set; }  
     public static void addNum(int a, int b)  
     {  
       Console.WriteLine(a + b.ToString() + " val");  
     }  
     public static void subNum(int a, int b)  
     {  
       Console.WriteLine(a + b.ToString() + " val");  
     }  
   }  
 }  
  • The output of above code is as follows in





No comments

Powered by Blogger.