heltonbiker
heltonbiker

Reputation: 27605

Getting instances from a list of types

I have the following code, but I cannot make it to run. All I want to create a list of instances from a given list of types.

List<Type> types = new List<Type>
{
    typeof(String),
    typeof(Double),
    typeof(Object)
};

List<object> instances = types.Select(t => Activator.CreateInstance(t) as t);

I get the error

> t is a variable but is used like a type

Upvotes: 1

Views: 388

Answers (1)

Alex Krupka
Alex Krupka

Reputation: 730

The compile error here is due to the fact that by saying as t you're not allowing the compiler to auto cast it to type object. This code is still buggy as it requires that all types in the list have default constructors (string does not have a default constructor).

Upvotes: 2

Related Questions