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)
Creating Object of a Class dynamically when you have name of the Class as string in C#?
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:
Hope it helped you. :)
Here is the Solution.
Consider below helper method: (change the namespace, version and public key tokens accordingly)
public static Type GetTypeFromClassName(string ClassName)For explanation of above method, read my below post.
{
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;
}
Creating Object of a Class dynamically when you have name of the Class as string in C#?
string ClassName="MyClass";Explanation:
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});
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.CommonYou can also get all the methods of this class by below code:
{
public class MyClass
{
//class properties
public List<Employee> MyMethod(string dept)
{
List<employees> emps=new List<employees> ();
//.................
// operations....
//...............
return employees;
}
}
}
MethodInfo[] methods= ClassType.GetMethods();
Hope it helped you. :)
Comments
Post a Comment