Wednesday, April 17, 2013

Calling a method in string in asp.net c#, like eval() in javascript

Sometimes, in ASP.Net and C# you need to call a particular method in a string dynamically, and then process the results if returned. For this we need to make use of : 

 
 
/// Summary: This function executes the given method in the namespace provided.
/// Param name="nameSpace" : Full namespace where the function exists.
/// Param name="constructorArgs": Arguments for the constructor (if any, else pass null).
/// Param name="methodName" : Name of the method to execute. Make sure the method is public.
/// Param name="methodArgs" : Arguments for the constructor (if any[in the same sequence], else pass null).
/// Returns : Returns back any object from that method (if any).
public static object InvokeThisMethod(string nameSpace, object[] constructorArgs, string methodName, object[] methodArgs)
{
 Type type = Type.GetType(nameSpace);
 object instance = Activator.CreateInstance(type, constructorArgs);
 MethodInfo method = type.GetMethod(methodName);
 return method.Invoke(instance, methodArgs);
}
 


For example: Consider these methods -

namespace Test
{
  public class Methods
  { 
    public void Method1() { // foo1 ...  }
    public void Method2() { // foo2 ...  }
    public void Method3() { // foo3 ... }
  }
}



Now in a situation, i want to call these methods(depending on the iteration) from a loop, I can call these methods as:

for (int i = 1; i <= 3; i++)
{  object[] obj = new object[] { };
  string methodName = "Method" + i;               
  InvokeThisMethod("Test.Methods", null, methodName, obj);
}




Enjoy,
 

No comments: