Reed
Reed

Reputation: 1642

How to pass a Class constructor or Type as a parameter

I am looking to dynamically construct an object from it's type or constructor.

var typeList = new List<Type>();
typeList.Add(String); // Error: 'string' is a type, which is not valid in this context
typeList.Add(CustomObject); // Error: 'CustomObject' is a type, which is not valid in this context

Because I want to do something among the lines of

// Pseudo code
foreach(var t in typeList){
  var obj = new t();
}

Upvotes: 0

Views: 78

Answers (2)

Rand Random
Rand Random

Reputation: 7440

If you only need the list to initial an object you could change the list from List<Type> to List<Func<object>> and use it like this

var initList = new List<Func<object>>();
initList.Add(() => string.Empty);
initList.Add(() => new CustomClass());

foreach (var init in initList)
    Console.WriteLine(init());

See it in action https://dotnetfiddle.net/ubvk20

Though I must say that I believe that there would be a better, more ideal, solution to the problem you are trying to solve.

Upvotes: 4

Joshua Robinson
Joshua Robinson

Reputation: 3539

If you have a List<Type> then you have to use typeof in order to get the actual Type instance for a given class.

var typeList = new List<Type>();

typeList.Add(typeof(string));
typeList.Add(typeof(CustomClass));

In order to create instances of the Types stored in typeList, you can use the Activator class. Specifically, Activator.CreateInstance.

foreach (var type in typeList)
{
   var inst = Activator.CreateInstance(type);
}

However, this still has some problems that you'll have to solve. For example, inst in the code above will be a reference to an object. You'll have to figure out some way to cast that to whatever type is if you want to use it as an instance of that type.

Also, the code above will only work for types which have a constructor which takes no parameters. If a type in typeList doesn't have a parameterless constructor, the code above will throw a MissingMethodException. This is especially worth mentioning, because in your example you're adding string to typeList, but string does not have an empty constructor.

Upvotes: 3

Related Questions