Wednesday, March 24, 2010

Invoke method using reflection


We have find out methods of any class using reflection but sometime we need to execute it using reflection.

For example, it might required that you have one logic for calculating pricing information which change time to time then you have to use reflection to calculate price. You can create one assembly to calculate pricing information. Whenever you need to change logic, you have to put new assembly on the same path with new logic.

Before calling any method you have to declare object of that class. You can use Activator class to create object runtime.


object objClass1 = Activator.CreateInstance(type);


The above code will create Class1 object using Activator class.

After loading class object successfully, you have to find out method from that type and invoke it. Following source code helps you to invoke method.


Assembly assembly = Assembly.Load("TestLibrary1");
Type t = assembly.GetType("TestLibrary1.Class1");
MethodInfo method = t.GetMethod("GetSum");
object objClass1 = Activator.CreateInstance(t);
object[] objParameters = new object[2];
objParameters[0] = 10;
objParameters[1] = 11;
MessageBox.Show(method.Invoke(objClass1, objParameters).ToString());


Here we load assembly and find out the class type using “GetType” method of assembly class. After getting class type, we have created class object dynamically using Activator class. Then we find out method which we need to invoke and also create parameter array to pass into method. After creating parameter array, we need to call “Invoke” method of MethodInfo class to invoke the method. Return value of Invoke method is the same which that method returns.

You can download source code from here.

No comments:

Post a Comment

DotNet Code Guru