Reflection in C#

To Achieve Reflection we have to use System.Reflection namespace contains classes and interfaces that provide a managed view of loaded types, methods, and fields, with the ability to dynamically create and invoke types.

Here are the few Methods we have uses to investigate a user Object.

  • GetMethods()
  • GetProperties()
  • GetConstructors()

Example:

  1. class Program {  
  2.     static void Main(string[] args) {  
  3.         Console.WriteLine("Enter the Library Type :");  
  4.         Type T = Type.GetType(Console.ReadLine());  
  5.         MethodInfo[] med = T.GetMethods();  
  6.         Console.WriteLine("************List Of Methods*****************");  
  7.         Console.BackgroundColor = ConsoleColor.Blue;  
  8.         foreach(var item in med) {  
  9.             Console.WriteLine(item);  
  10.         }  
  11.         Console.BackgroundColor = ConsoleColor.Black;  
  12.         Console.WriteLine("************List Of Properties*****************");  
  13.         Console.BackgroundColor = ConsoleColor.Yellow;  
  14.         PropertyInfo[] prop = T.GetProperties();  
  15.         foreach(var item in prop) {  
  16.             Console.WriteLine(item);  
  17.         }  
  18.         Console.BackgroundColor = ConsoleColor.Black;  
  19.         Console.WriteLine("************List Of Constructor*****************");  
  20.         Console.BackgroundColor = ConsoleColor.Green;  
  21.         Console.ForegroundColor = ConsoleColor.Black;  
  22.         ConstructorInfo[] ctr = T.GetConstructors();  
  23.         foreach(var item in ctr) {  
  24.             Console.WriteLine(item);  
  25.         }  
  26.         Console.BackgroundColor = ConsoleColor.Black;  
  27.         Console.ReadLine();  
  28.     }  
  29. }