C# instantiate generic List from reflected Type?

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).

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).

1 for typeof(List), I hadn't seen this before. – Wesley Wiser Jan 11 at 18:35 does var exist in . Net framework 2.0?!

– sprocketonline Jan 11 at 19:30 @sprocketonline: var is a C# 3 feature so if you are using C# 2 you will need to declare your variables explicitly. – Andrew Hare Jan 11 at 19:52.

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; }.

1 for remember the good old non generic supported interfaces :) – leppie Jan 11 at 18:49.

You can use MakeGenericType for such operations. For documentation, see here and here.

Var constructedListType = listType. Var instance = Activator. // can work with it and use it to some degree.

Var instance = (IList)Activator.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions