Abdulla
Abdulla

Reputation: 1127

Create List of Type customType

I am trying to create a list of a custom type that is set at runtime. How is this possible?

Here is my code:

Type customType = typeof(string); // or someOtherVariable.GetType();

List<customType> ls = new List<customType>(); // Error: The type or namespace name `customType' could not be found

Upvotes: 3

Views: 3805

Answers (2)

Jason Coyne
Jason Coyne

Reputation: 6636

You cannot do this. Generics collections are strongly typed at compile time. You could perhaps emit/codegen a new class and compile it on the fly when needed, but that is a very different problem

Upvotes: -1

Justin Niessner
Justin Niessner

Reputation: 245419

If you want to instantiate a generic list of some reflected type, you'll have to use Reflection to do so:

var type = typeof(string);

var list = typeof(List<>);
var listOfType = list.MakeGenericType(type);

var instance = Activator.CreateInstance(listOfType);

Upvotes: 7

Related Questions