0

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(); } 
4
  • 4
    Use typeof(string) Commented Jul 31, 2020 at 16:23
  • string str = (string)System.Activator.CreateInstance(typeof(string)); Commented Jul 31, 2020 at 16:25
  • @RandRandom is there a different declaration I could use for the T of List that would allow me to pass the Class names in without typeof? Commented Jul 31, 2020 at 16:27
  • 1
    You can also have a List<Func<object>>(), then list.Add(() => new object()), list.Add((() => new string()), then foreach (var t in list} { var obj = t(); }. This isn't a list of types, but rather it's a list of delegates, each of which knows how to create an instance of a particular type Commented Jul 31, 2020 at 16:36

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.