0

I have an Unpack() function that takes a generic parameter T where T is a class i.e.

var test = Unpack<ExampleClass>();

The above example works fine, but I am in a situation where I need to do the same as above, but I only know the class/generic parameter name in a string. In other words, how can I do the same thing as above with:

string className = "ExampleClass";

instead of the class ExampleClass?

Roka545
  • 3,404
  • 20
  • 62
  • 106
  • 2
    You'll need to use Reflection. You should really show more of your code, but you can get a particular method of a Type (by name) as a MethodInfo. If it's generic, then you can combine it with the name of a type and get another MethodInfo representation a particular type-specific version of the method. Then you can Invoke it. (Caveat, this is from memory, but start with GetType [or typeof)) and go from there) – Flydog57 Aug 25 '19 at 01:36
  • Try to see if there is an overload of `Unpack` that takes a `Type` parameter instead. – Sweeper Aug 25 '19 at 01:46
  • 1
    If you only know it in a string, you only know it at run time. Generics must be resolved at compile time. – Joel Coehoorn Aug 25 '19 at 03:24
  • Possible duplicate of [How do I use reflection to call a generic method?](https://stackoverflow.com/questions/232535/how-do-i-use-reflection-to-call-a-generic-method) – thehennyy Aug 25 '19 at 11:32

1 Answers1

3

You could make use of MethodInfo.MakeGenericMethod

For example

You can divide the solution to two parts. First Get the Type of ExampleClass from string representation.

Type type = Type.GetType("ExampleNameSpace.ExampleClass");

Then use the MakeGenericMethod to invoke the method passing the type.

MethodInfo method = this.GetType().GetMethod(nameof(Unpack));
MethodInfo generic = method.MakeGenericMethod(type);
generic.Invoke(this, null);
Anu Viswan
  • 17,797
  • 2
  • 22
  • 51