Saturday, May 5, 2018

C# : What is Reflection in C#.Net

Reflection typically is the process of runtime type discovery to inspect metadata, CIL code, late binding and self-generating code. At run time by using reflection, we can access the same "type" information as displayed by the ildasm utility at design time. The reflection is analogous to reverse engineering in which we can break an existing *.exe or *.dll assembly to explore defined significant contents information, including methods, fields, events and properties.

You can dynamically discover the set of interfaces supported by a given type using the System.Reflection namespace. This namespace contains numerous related types as follows:

ASP.NET

Reflection typically is used to dump out the loaded assemblies list, their reference to inspect methods, properties etcetera. Reflection is also used in the external disassembling tools such Reflector, Fxcop and NUnit because .NET tools don't need to parse the source code similar to C++. 

Metadata Investigation 

The following program depicts the process of reflection by creating a console based application. This program will display the details of the fields, methods, properties and interfaces for any type within the mscorlib.dll assembly. Before proceeeding, it is mandatory to import "System.Reflection".

Here, we are defining a number of static methods in the program class to enumerate fields, methods and interfaces in the specified type. The static method takes a single "System.Type" parameter and returns void.
  1. static void FieldInvestigation(Type t) {  
  2.     Console.WriteLine("*********Fields*********");  
  3.     FieldInfo[] fld = t.GetFields();  
  4.     foreach(FieldInfo f in fld) {  
  5.         Console.WriteLine("-->{0}", f.Name);  
  6.     }  
  7. }  
  8.   
  9. static void MethodInvestigation(Type t) {  
  10.     Console.WriteLine("*********Methods*********");  
  11.     MethodInfo[] mth = t.GetMethods();  
  12.     foreach(MethodInfo m in mth) {  
  13.         Console.WriteLine("-->{0}", m.Name);  
  14.     }  
  15. }  

No comments:

Post a Comment