Thursday, April 19, 2012

Invoke any Method Dynamically


Objective:
To invoke any method in an instance dynamically by passing Method name as parameter.

Achieved by:
System.Reflection namespace which contains types that retrieve information about assemblies, modules, members, parameters, and other entities in managed code by examining their metadata.
Used MethodInfo Class - Discovers the attributes of a method and provides access to method metadata.

Hierarchy:
·          System.Object
o    System.Reflection.MemberInfo
§   System.Reflection.MethodBase
·          System.Reflection.MethodInfo

Method Used:
Invoke(Object, Object[]) - Invokes the method or constructor represented by the current instance, using the specified parameters.
Advantage:
·          Thread safe
·          Simple to use
·          Has the scalability for future enhancement.

My Implementation:

TestClass TestCl = new TestClass();
Type FuncType = typeof(TestClass);
MethodInfo miTest_Method = FuncType.GetMethod(“Test_Method”);
List lCodeList = new List();
object[] mParam = new object[] { lCodeList };
miTest_Method.Invoke(TestCl, mParam);// you can get the return of method as object

1 comment:

  1. Sir, What is the method signature and return type?

    ReplyDelete