Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a method on a static class given its type name and method names as strings

Tags:

c#

reflection

How could I go about calling a method on a static class given the class name and the method name, please?

For example:

Given System.Environment and GetFolderPath, I'd like to use Reflection to call Environment.GetFolderPath().

like image 263
Daniel Elliott Avatar asked Sep 13 '09 16:09

Daniel Elliott


People also ask

How do you call a static class method in C#?

Because there is no instance variable, we access the members of a static class by using the class name itself. C# fields must be declared inside a class. However, if we declare a method or a field as static, we can call the method or access the field using the name of the class. No instance is required.

Can a static and instance method have same name?

We currently do not allow two members declared in the same class to have the same name, even if one is static and the other is an instance member.

How can call static method from non static class in C#?

But when we try to call Non static function i.e, TestMethod() inside static function it gives an error - “An object refernce is required for non-static field, member or Property 'Program. TestMethod()”. So we need to create an instance of the class to call the non-static method.


2 Answers

Just

Type.GetType(typeName).GetMethod(methodName).Invoke(null, arguments);

where typeName is the name of the type as a string, methodName is the name of the method as a string, and arguments is an array of objects containing the arguments to call the method with.

like image 173
Daniel Brückner Avatar answered Oct 19 '22 14:10

Daniel Brückner


First you need to get the Type (by iterating on the assembly using reflection)

see this link for details: http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.aspx

or use

Assembly.GetType

once you have the type in hand you can iterate over members using reflection or

MethodInfo method = typeof(MyClass).GetMethod("MyMethod");

then you can use MethodInfo.Invoke and pass arguments to invoke the method when you want to invoke it.

like image 4
Ahmed Khalaf Avatar answered Oct 19 '22 12:10

Ahmed Khalaf