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. :) 

Comments

Popular posts from this blog

SharePoint Online (O365) OAuth Authentication | Authorizing REST API calls against SharePoint Online Site | Get Access token from SharePoint Online | Set up OAuth for SharePoint Online Office 365

SharePoint 2013 REST API Reference

Simple Risk Assessment Matrix table with resultant risk calculation

Kendo UI (Core JavaScript) grid Server Paging, Server Sorting and Server Filtering with Dynamic SQL queries

Sharepoint- Using an Image From formatmap32x32.png in a Ribbon Control