1

I have a string holding a type name. I want to get the type in reflection, and call a static method. I want to keep the code simple as possible. something like this:

public class MyClass {    
          static int foo() 
          {
             return 7;
          }; 
}

var MyClassType = Type.GetType("MyClass"); 
// your help here! 
int res = (MyClassType).foo();

Thanks!

0

2 Answers 2

5

You need to specify the correct binding flags to make this work:

// NOTE: Use full name for "MyClass", incuding any namespaces.
var myClassType = Type.GetType("MyClass");
int res = (int)myClassType.GetMethod("foo", BindingFlags.NonPublic | BindingFlags.Static).Invoke(null, null);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! Do I have to give the method name as string as well? Is there no way to cast it to the MyClass type?
@Adibe7 Yes, when using reflection you need to specify the method name as a string. (You're talking about "foo" here.) Did you mean "the class name"? If it's really the class then you can just do: var myClassType = typeof(MyClass);
0

Try like this:

int res = Type.GetType("MyClassType").GetMethod("foo").Invoke(null, null);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.