Reflection also goes one step further; it can also invoke a member which is inspected. For instance if the reflection detects that there is a method called as “GetChanges” in an object. We can get a reference to that method instance and invoke the same on runtime.
In simple words reflection passes through two steps “Inspect” and “Invoke” (optional). “Invoke” process is optional.
Implementing reflection in c# is a two step process , 1st get the “type” of the object and then use the type to browse members like “methods” , “properties” etc.
Step 1: - The first step is to get the type of the object. So for example you have a DLL called as “ClassLibrary1.dll” which has a class called as “Class1”. We can use the “Assembly” (belongs to 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 reference to the type of the object.
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 reference the type of the object we can then call “GetMembers” or “GetProperties” to browse throw the methods and properties of the class.
foreach (MemberInfo objMemberInfo in parameterType.GetMembers())
// Browse through properties.
In case you want to invoke the member which you have inspected you can use “InvokeMember” to invoke the method. Below is the code for the same.
BindingFlags.Instance,null, objMyClass, null);
Practical uses of reflection
- If you are creating application like visual studio editors where you want show internal of an object by using intellisense.
- In unit testing sometimes we need to invoke private methods. That’s a different thing test private members are proper or not.
- Sometimes we would like to dump properties, methods and assembly references to a file or probably show it on a screen.