Reputation: 2209
Consider the following class:
public class GenericClass<T>
{
public T Argument;
}
And a second class that references and uses the GenericClass:
public class ClientClass
{
GenericClass<T> genclass = new GenericClass<T>();
}
My problem is that I don't know the type of T at compile time. I am using reflection during runtime to obtain the type of T. Is it possible somehow to use a parametrized expression while instantiating the GenericClass
?
Upvotes: 2
Views: 1612
Reputation: 39823
Yes, but you'll have to use reflection to build the actual type for which you're looking.
You first need to get the open generic, by using the typeof
operator:
var openType = typeof(GenericClass<>);
Next, you need to build the specific generic you want. Say your desired type T is stored in a variable, type
:
var closedType = openType.MakeGenericType(type);
Finally, use reflection to create an instance of that type.
object instance = Activator.CreateInstance(closedType);
As noted by xanatos in the comments, however, you should be aware that this results in a member of type object
. To be able to manipulate the object without reflection, you have two choices.
GenericClass
, from which GenericClass<T>
derives, and include methods on it that are common to all. (i.e. GenericClass
contains members that don't need to use T
.IInterface
, and then add a restriction on T
, where T : IInterface
. Then, you can cast instance
to GenericClass<IInterface>
and manipulate it that way. Obviously, type
must implement IInterface
in this case.You can of course also just keep the object
reference and manipulate it using reflection only, or use dynamic
to late-bind any method calls -- this uses reflection under the hood, however.
Upvotes: 5