Friday, 13 February 2015

C#: How to dynamically invoke a method from a Class, when you know the ClassName and Method Name as string

How to invoke a method from a Class, when you know the ClassName and Method Name as string in C#.
Here is the Solution.

Consider below helper method: (change the namespace, version and public key tokens accordingly)
 public static Type GetTypeFromClassName(string ClassName)
        {
            string ss = string.Format("Solutions.Common.{0}, Solutions.Common, Version=1.0.0.0, Culture=neutral, PublicKeyToken=3a6a3aa5a3aed1e3", ClassName);
            Type typeYouWant = Type.GetType(ss);
            if (typeYouWant != null)
            {
                return typeYouWant;
            }
            return null;
        }
For explanation of above method, read my below post.
Creating Object of a Class dynamically when you have name of the Class as string in C#?


string ClassName="MyClass";
string MethodName="MyMethod";
string param1="IT";
Type ClassType = GetTypeFromClassName(ClassName);
var myObj = Activator.CreateInstance(ClassType);
MethodInfo method = ClassType.GetMethod(MethodName);
var ReportData = method.Invoke(myObj, new object[] { param1});
Explanation:
First , get the type of the Class using GetTypeFromClassName
Create the object of the class. Activator.CreateInstance does this job.
Get the method by method name. Type.GetMethod(methodNme).
Invoke the method. method.Invoke.
param1 is the parameter which is getting sent to MyMethod function.

For the above scenario, your Class and method would have defined this way:

namespace Solutions.Common
{
    public class MyClass
    {
       //class properties
       public List<Employee> MyMethod(string dept)
        {
             List<employees> emps=new List<employees> ();
             //.................
            // operations....
            //...............
            return employees;
         }
     }
}
You can also get all the methods of this class by below code:

 MethodInfo[] methods= ClassType.GetMethods();

Hope it helped you. :)