Ege Aydın
Ege Aydın

Reputation: 1081

Use classes static method when you only have the type name of the class as a string

I am wondering if it is possible to use a classes method when you only know the classes name by it's string value.

Let's say I have a class and within class I have a static method like

public class SomeClass 
{
    public static string Do()
    {
         //Do stuff
    }
}

And when using class I want to something like

string str = (GetType(SomeClass)).Do();

When using the method I want to give the name of the class as string like I want to give SomeClass as a string.

Upvotes: 0

Views: 87

Answers (3)

Asad Saeeduddin
Asad Saeeduddin

Reputation: 46628

var t = Type.GetType("MyNamespace.SomeClass");
var m = t.GetMethod("Do");

m.Invoke(null, new object[] { /* Any arguments go here */ });

Upvotes: 3

poke
poke

Reputation: 387507

Use Type.GetMethod to get the method info object of the method, then call MethodInfo.Invoke to execute it. For static methods, pass null as the first parameter (the object value):

Type type = typeof(SomeClass);
type.GetMethod("Do").Invoke(null, null);

If you don’t know the class name at compile time, you can also use object.GetType, Type.GetType or Assembly.GetType to get the type object at runtime (depending on what information you have available). Then, you can use it in the same way:

Type type = someObject.GetType(); // or Type.GetType("SomeTypeName");
type.GetMethod("Do").Invoke(null, null);

To be on the safe side, make sure to check whether GetMethod actually returns a method, so you have some confirmation that the method exists on that type then.

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1062502

You're going to have to use reflection throughout; for example:

object result = Type.GetType(typeName).GetMethod(methodName).Invoke(null, args);

Upvotes: 1

Related Questions