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!

Adibe7
  • 3,469
  • 7
  • 30
  • 36

2 Answers2

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);
Matthew Watson
  • 104,400
  • 10
  • 158
  • 276
  • 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 Aug 05 '13 at 14:43
  • @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);` – Matthew Watson Aug 05 '13 at 15:00
0

Try like this:

int res = Type.GetType("MyClassType").GetMethod("foo").Invoke(null, null);
Romano Zumbé
  • 7,893
  • 4
  • 33
  • 55