Fernando
Fernando

Reputation: 1259

specifying a generic type parameter using a string

Suppose I have a method

public void Whatever<T>() { ... }

suppose I have a type in the form of a string

var myType = "System.String";

Normally, I'd call the method like:

Whatever<string>();

But I'd like to be able to call it using myType somehow. Is this possible? I know this doesn't work, but conceptually:

Whatever<Type.GetType(myType)>();

Upvotes: 1

Views: 81

Answers (2)

Bazzz
Bazzz

Reputation: 26932

You can use Reflection and MethodInfo.MakeGenericMethod for this

Reflect the method that you want to call to get the MethodInfo, then make it generic and Invoke it.

Something like this (notice that this is from the top of my head (no VS here), it might not be perfect yet but should get you started):

Type type = myObject.GetType();
MethodInfo method = type.GetMethod("NameOfMethod");
MethodInfo genericMethod = method.MakeGenericMethod(typeOf(string));
genericMethod.Invoke(myObject, new object[] { "theString" } );

Upvotes: 2

Adriano Repetti
Adriano Repetti

Reputation: 67128

You can create an instance via Reflection (or provide both generic and non-generic Whatever type). Of course Reflection is slow (and you can have only an object or base class reference). Often the generic type can be just a specialization of the non-generic one.

Upvotes: 0

Related Questions