Reputation: 8721
I'm trying to use a generic List<T>
custom class MyList<T>
for automated items parsing and I'm stuck at creating a return type of MyList<T>
. Specifically I don't know how to create such a list with the given type. One thing I can do is find out the type and store it in a Type itemType
variable.
This question helped me find out the type of list items.
The catch is I don't know the list type until runtime, so it can't be written explicitly in code.
How do I create a list of items of a certain type using a Type itemType
variable?
Upvotes: 1
Views: 92
Reputation: 456
You can do this using Reflection, for example:
var listType = typeof(List<>);
listType.MakeGenericType(typeof(MyType))
return Activator.CreateInstance(listType);
Another example, if all you have is an instance of "MyType" but don't know what it is until runtime:
public IEnumerable GetGenericListFor(object myObject){
var listType = typeof(List<>);
listType.MakeGenericType(myObject.GetType())
return Activator.CreateInstance(listType);
}
Upvotes: 2
Reputation: 12754
Here is the corresponding MSDN article about dynamically creating generic types given the generic type, and the parameter types. Scroll to "Constructing an Instance of a Generic Type" section around the middle.
Quick sample:
Type d1 = typeof(Dictionary<,>);
Type[] typeArgs = {typeof(string), typeof(int)};
Type constructed = d1.MakeGenericType(typeArgs);
object o = Activator.CreateInstance(constructed);
Upvotes: 0