panipsilos
panipsilos

Reputation: 2209

Construct an instance of a concrete type of a generic, using reflection at runtime

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

Answers (1)

David Pfeffer
David Pfeffer

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.

  1. You can create a parent class, 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.
  2. As Ingenu had mentioned in the comments on the question, you can create an interface 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

Related Questions