Wednesday, May 9, 2012

Execute functions dynamically using Reflection


Using Reflection you can execute any methods or constructor dynamically. This is something on the line of functional pointer but with some improvement. One of the notable improvements is unlike functional pointer you can pass the method name in string variable to execute.

There are couple of ways to do that and both the ways are described below.

What’s the use of it – for me I had a specific requirement of retrieving list of data in List for further use. But this implementation needed and generic and user friendly approach. In future if there is a requirement of separate list then it can be added easily.

Implementation

Functionality for creating list

public class TestClass
{
      void _LIST(List<string[]> lList, string sNumber, string sAlphaData)
      {
            string[] sData = new string[2];
            sData[0] = sNumber;
            sData[1] = sAlphaData;
            lList.Add(sData);
      }
//Sample functions which will be called dynamically
//If you observe the functions for adding a new list user need to add new function in the format
//below and using a generic function call it dynamically
      public void function_1(List<string[]> lTestList)
      {
            _LIST(lTestList, "0", "Test 1");
            _LIST(lTestList, "2", "Test 2");
      }
      public void function_2(List<string[]> lTestList)
      {
            _LIST(lTestList, "A", "Alpha 1");
            _LIST(lTestList, "B", "Alpha 2");
      }
}

Generic function which has one parameter (string) in which function name will be passed.
This generic function can be implemented in couple of ways:

Using Activator
public string ExecuteFunction(string sFunationName)
{
      List<string[]> lTestList = new List<string[]>();
      Type FuncType = this.GetType();
      object[] mParam = new object[] { lTestList };
      object obj = Activator.CreateInstance(FuncType);
      FuncType.InvokeMember(sFunationName, BindingFlags.InvokeMethod, null, obj, mParam);
      // at this point lTestList get populated with data which can be used as per user discretion
}

Using Reflection
public string ExecuteFunction(string sFunationName)
{
      TestClass testClass = new TestClass();
      List<string[]> lTestList = new List<string[]>();
      Type FuncType = typeof(TestClass);
      MethodInfo miFunationName = FuncType.GetMethod(sFunationName);
      object[] mParam = new object[] { lTestList };
      miFunationName.Invoke(testClass, mParam);
      // at this point lTestList get populated with data which can be used as per user discretion
}

No comments:

Post a Comment