Tuesday, August 18, 2015

Reflection and Dynamic keyword in C#

Disclaimer : It's self study material, either directly produced/copied or modified as needed to suit                              "MY" understanding. Giving specific credits is little difficult. In-case of any concern                            seeing your wordings being presented here , please feel free to write, will try to remove                        or  add credits as demanded.
Credits : C#,VB.Net books, article, blogs, msdn etc.



Why do we need Reflection
Reflection is needed when you want to determine / inspect contents of an assembly. For example look at your Visual Studio editor intellisense, when you type “.” (dot) before any object, it gives you all the members of the object. This is possible because of Reflection.
                                                     
Reflection can also invoke a member which is inspected. For instance if Reflection detects that there is a method called GetChanges in an object, we can get a reference to that method instance and invoke it on runtime.
In simple words Reflection passes through two steps: “Inspect” and “Invoke” (optional). The "Invoke" process is optional.

How to implement Reflection
Implementing reflection in c# is a two step process :
1. Get the “type” of the object
2. Use the type to browse members like “methods” , “properties” etc.

Step 1:
First step is to get the type of the object.
Example:
If you have a DLL ClassLibrary.dll which has a class called Class1. We can use the Assembly (belongs to the System.Reflection namespace) class to get a reference to the type of the object.
Later we can use Activator.CreateInstance to create an instance of the class.
The GetType() function helps us to get a reference to the type of the object.

Code snippet

var myAssembly = Assembly.LoadFile(@"C:\ClassLibrary1.dll");
var myType = myAssembly.GetType("ClassLibrary1.Class1");
dynamic objMyClass = Activator.CreateInstance(myType);
// Get the class type
Type parameterType = objMyClass.GetType();

Step 2:
Once we have a reference of the type of the object we can then call GetMembers or GetProperties to browse through the methods and properties of the class.

Code snippet

// Browse through members
foreach (MemberInfo objMemberInfo in parameterType.GetMembers())
{Console.WriteLine(objMemberInfo.Name);}

// Browse through properties.
foreach (PropertyInfo objPropertyInfo in parameterType.GetProperties())
{Console.WriteLine(objPropertyInfo.Name);}

     In case if we want to invoke the member which you have inspected, you can use InvokeMember to invoke the method. Below is the code:

Code snippet

parameterType.InvokeMember("Display",BindingFlags.Public |
BindingFlags.NonPublic | BindingFlags.InvokeMethod |

BindingFlags.Instance,null, objMyClass, null);



No comments:

Post a Comment