Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create instance of class and call method from string

Tags:

c#

reflection

String ClassName =  "MyClass"
String MethodName = "MyMethod"

I would like to achieve:

var class = new MyClass; 
MyClass.MyMethod();

I saw some e.g. with reflection , but they only show , either having a method name as string or class name as string, any help appreciated.

like image 919
Zaid Kajee Avatar asked May 25 '26 13:05

Zaid Kajee


1 Answers

// Find a type you want to instantiate: you need to know the assembly it's in for it, we assume that all is is one assembly for simplicity
// You should be careful, because ClassName should be full name, which means it should include all the namespaces, like "ConsoleApplication.MyClass"
// Not just "MyClass"
Type type = Assembly.GetExecutingAssembly().GetType(ClassName);
// Create an instance of the type
object instance = Activator.CreateInstance(type);
// Get MethodInfo, reflection class that is responsible for storing all relevant information about one method that type defines
MethodInfo method = type.GetMethod(MethodName);
// I've assumed that method we want to call is declared like this
// public void MyMethod() { ... }
// So we pass an instance to call it on and empty parameter list
method.Invoke(instance, new object[0]);
like image 122
JustSomeGuy Avatar answered May 28 '26 01:05

JustSomeGuy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!