gerg
gerg

Reputation: 771

Get class definition from type

I have a situation where I'd like to be able to pass a Type as a generic parameter. My problem is that once I use typeof() to obtain a Type, I cannot figure out how to get this back into a form that would allow me to pass it as a generic parameter, even though the type is still a class type.

The below is purely to demonstrate my issue, I'm not actually calling typeof() on something that's already constrained as a class type:

public void Example<T>() where T : class
{
  //This works fine.
  var firstList = new List<T>();

  Type aType = typeof(T);

  //This resolves to true.
  bool thisIsTrue = aType.IsClass;

  //This does not compile?!?
  var secondList = new List<aType>();
}

Answering any of the following questions would likely solve my issue:

-- Is there a command similar to typeof(), .GetType(), etc., that would allow me to constrain the result to a class, so the compiler would accept it for a generic parameter? Then I could avoid the issue of going from type to class altogether.

-- Is there actually a way to transform a type into a class? I couldn't find a way to do it from either the type or an instantiated object of said type.

-- As a last resort, am I going to need to dynamically define these classes at runtime to actually get this to work?

Upvotes: 9

Views: 12607

Answers (1)

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101701

You are looking for MakeGenericType method

var secondListType = typeof(List<>).MakeGenericType(aType);
var secondList = (List<T>)Activator.CreateInstance(secondListType);

Upvotes: 5

Related Questions