What is Reflection in C#.Net with Example?

Views: 281
Created Date: 12-Sep-2016

Reflection is a concept of reading the metadata at runtime. System.Reflection.InvokeMember is used to invoke a method dynamically at runtime. Once you have an object reference to the assembly of interest, you can call the GetTypes method on that assembly, which returns an array of all the types in that assembly. You can use control logic to identify more specific types in that array, and use iterating logic to parse your array, returning the type information to the user if needed. The ability to retrieve type information can be useful for determining alternative types you could use for a given task, or identifying existing elements which could provide you with the functionality you need. The first thing to learn when retrieving types from a particular assembly is, how to identify an assembly. The first is by identifying a particular object that you want to find the assembly of, and requesting the assembly for the module of that object (remember that a module is a logical grouping of types and code, such as a .dll or .exe). The second is by using the LoadFrom method of the Assembly class to load a specific assembly for a named module (such as mypgm.exe).

class CMain
 
 {
 
     static void Main(string[] args)
 
     {
 
         //Step 1 : Load an Assembly
 
         Assembly asm = Assembly.LoadFrom("C:\\Karthik Documents\\MathLibrary.dll");
 
         //Step 2 : Get the Modules
 
         Module[] modules = asm.GetModules();
 
 
 
         foreach (Module mod in modules)
 
         {
 
             Console.WriteLine("module {0}", mod.Name);
 
             //Step 3 : Get types
 
             Type[] types = mod.GetTypes();
 
 
 
             foreach (Type t in types)
 
             {
 
                 Console.WriteLine("Type {0}", t.Name);
 
                 //Step 4 : Get Methods
 
                 MethodInfo[] methods = t.GetMethods();
 
 
 
                 foreach (MethodInfo method in methods)
 
                 {
 
                     Console.WriteLine("method : {0}", method.Name);
 
                 }
 
                 FieldInfo[] fields = t.GetFields();
 
                 foreach (FieldInfo field in fields)
 
                 {
 
                     Console.WriteLine("field : {0}", field.Name);
 
                 }
 
             }
 
         }
 
     }
 
 }

Similar Tags
2.9 173