Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create list of variable type

Tags:

c#

list

I am trying to create a list of a certain type.

I want to use the List notation but all I know is a "System.Type"

The type a have is variable. How can I create a list of a variable type?

I want something similar to this code.

public IList createListOfMyType(Type myType) {      return new List<myType>(); } 
like image 613
Jan Avatar asked Mar 22 '10 14:03

Jan


People also ask

How do you create a List variable type?

To create the instance we should use System. Activator. CreateInstance(myType). But then again, the return value if an object of type myType.

Can you make a List of lists in C#?

A simple solution for constucting a List of Lists is to create the individual lists and use the List<T>. Add(T) method to add them to the main list. The following example demonstrates its usage. That's all about creating a List of Lists in C#.


2 Answers

Something like this should work.

public IList createList(Type myType) {     Type genericListType = typeof(List<>).MakeGenericType(myType);     return (IList)Activator.CreateInstance(genericListType); } 
like image 146
smencer Avatar answered Sep 29 '22 13:09

smencer


You could use Reflections, here is a sample:

    Type mytype = typeof (int);      Type listGenericType = typeof (List<>);      Type list = listGenericType.MakeGenericType(mytype);      ConstructorInfo ci = list.GetConstructor(new Type[] {});      List<int> listInt = (List<int>)ci.Invoke(new object[] {}); 
like image 40
Andrew Bezzub Avatar answered Sep 29 '22 12:09

Andrew Bezzub