When we write non-trivial software that should go to production, it is mandatory to have the ability to load and execute modules on the fly. This is useful when you are planning to provide user defined extensions as a mechanism to add new features to the existing software. The .NET Reflection API is a nifty mechanism supported by the Microsoft Corporation to help developers to write code that can be loaded dynamically, after the base software has been written. The platform technologies, such as ASP.net, WCF,EF, and WPF, use reflection extensively:
public class Test { //---- Only Property this class has public int X { get; set; } //----- This method will be invoked dynamically public void Spit() { Console.WriteLine(" X is " + X); } }
We will write a simple program that will instantiate the object using the new
keyword, and after the object instantiation, a property (X
) will be set to the value 0xBEEF
. The .NET Reflection API will be used to retrieve the property value and invoke a method (Spit
) using them:
class Program { static void Main(string[] args) { Test a = new Test(); //------ Set the property a.X = 0xBEEF; //------ Retrieve the CLR Type Type t = a.GetType(); if (t == null) return; //---- Retrieve the Property Handle PropertyInfo np = t.GetProperty("X"); //---- Retrieve the Property Value Console.WriteLine(np.GetValue(a)); //------ Retrieve the Method Handle MethodInfo mi = t.GetMethod("Spit"); //------ Invoke the method mi.Invoke(a, null); Console.Read(); } }
We will be using .NET Reflection API extensively in our programs. A competent programmer should know the .NET Reflection API and its features to write any advanced piece of code. Do consult the Microsoft documentation to understand the features available and the nuances of the API. If you want to be a library or framework designer, you should know Reflection API in depth.
3.145.119.199