Search code examples
c#genericsreflectioneval

Calling method with generic type using class name as string


Having this class :

class ClassA{
}

and a method with this signature:

void MyMethod<T>();

All we use it on this way:

MyMethod<ClassA>();

But... exist some chance of call MyMethod having the class name as string?. I.e.:

var className = "ClassA";

MagicMethod($"MyMethod<{className}>();");

Im talking about some equivalent of Eval in JavaScript. Reflection?, Any idea?

I googled some libraries like DynamicExpresso but nothing with support for generic types.

About possible duplicates:


Solution

  • Providing you have the following method:

    public class Foo
    {
         public void MyMethod<T>();
    }
    

    You may get the MethodInfo:

    MethodInfo methodInfo = typeof(Foo).GetMethod("MyMethod");
    

    Now, let's say you have this class:

    public class exampleB
    {
    }
    

    You can invoke the generic method using the generic parameter type's name:

    string genericTypeName = "exampleB";
    Type genericType = Type.GetType(genericTypeName);
    MethodInfo methodInfo = typeof(Foo).GetMethod("MyMethod").MakeGenericMethod(genericType);
    
    // You will need an instance of Foo to invoke it (the method isn't static)
    methodInfo.Invoke(fooInstance, null);
    

    Of course, this will require the run-time to search for type B, so you should be careful and specify the correct namespace too.