C# instantiate generic List from reflected Type

C#ReflectionGenerics

C# Problem Overview


Is it possible to create a generic object from a reflected type in C# (.Net 2.0)?

void foobar(Type t){
    IList<t> newList = new List<t>(); //this doesn't work
    //...
}

The Type, t, is not known until runtime.

C# Solutions


Solution 1 - C#

Try this:

void foobar(Type t)
{
    var listType = typeof(List<>);
    var constructedListType = listType.MakeGenericType(t);

    var instance = Activator.CreateInstance(constructedListType);
}

Now what to do with instance? Since you don't know the type of your list's contents, probably the best thing you could do would be to cast instance as an IList so that you could have something other than just an object:

// Now you have a list - it isn't strongly typed but at least you
// can work with it and use it to some degree.
var instance = (IList)Activator.CreateInstance(constructedListType);


Solution 2 - C#

static void Main(string[] args)
{
  IList list = foobar(typeof(string));
  list.Add("foo");
  list.Add("bar");
  foreach (string s in list)
    Console.WriteLine(s);
  Console.ReadKey();
}

private static IList foobar(Type t)
{
  var listType = typeof(List<>);
  var constructedListType = listType.MakeGenericType(t);
  var instance = Activator.CreateInstance(constructedListType);
  return (IList)instance;
}

Solution 3 - C#

You can use MakeGenericType for such operations.

For documentation, see here and here.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionIain SproatView Question on Stackoverflow
Solution 1 - C#Andrew HareView Answer on Stackoverflow
Solution 2 - C#csauveView Answer on Stackoverflow
Solution 3 - C#Ilya KoganView Answer on Stackoverflow