2

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:

Community
  • 1
  • 1
Sebastián Guerrero
  • 1,055
  • 1
  • 19
  • 26
  • Or ```Type t = Type.GetType(string_name_of_type);```, more docs [here](https://msdn.microsoft.com/en-us/library/w3f99sx1(v=vs.110).aspx) – Daniel Gruszczyk Nov 17 '15 at 16:31
  • 2
    I think is not same case in [Calling a function from a string in C#](http://stackoverflow.com/questions/540066/calling-a-function-from-a-string-in-c-sharp) because that sample not use Generics Types. – Sebastián Guerrero Nov 17 '15 at 16:31
  • @Alexander, I don't think this is duplicate... – Daniel Gruszczyk Nov 17 '15 at 16:35
  • 1
    @DanielGruszczyk, we need to use reflection and as I understand problem is to call generic method. And it is what "Use Reflection to call..." question about – Alexander Nov 17 '15 at 16:39

1 Answers1

4

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.

Pravin Sharma
  • 1,160
  • 1
  • 8
  • 20
Matias Cicero
  • 25,439
  • 13
  • 82
  • 154