tags:

views:

132

answers:

3

Hello all,

Since I can't make any comments (only post an answer) to this post, I'll post a new question.
I followed the instructions from mentioned post, but the code produces an error.
The code:

Type t = Type.GetType(className);
Type listType = typeof(List<>).MakeGenericType(t);
IList list = (IList)Activator.CreateInstance(listType);

The error:
"Using the generic type 'System.Collections.Generic.IList' requires '1' type arguments"

Clearly I can't just state IList without any type, so I'm wondering how exactly does the answer from the mentioned post works.

Thanks in advance.

+3  A: 

You can, you just need a different using directive:

using System.Collections;

That way you'll be using the nongeneric IList instead of the generic IList<T>.

I believe that's the spirit of the referenced answer.

Jon Skeet
@Jon, Superman could take lessons from you on how to be everywhere he's needed in the blink of an eye. :-p
LBushkin
Yep, that's the one, thanks a lot.
Dejan
A: 

Are you trying to create a generic IList through reflection?

48klocs
Yes. I skipped that post somehow. I searched a lot before posting a question. Anyway, the code I posted works like a charm, I just needed right using directive, like Jon posted. Thanks for the link.
Dejan
A: 
Type t = Type.GetType(className);
Type listType = typeof(List<>).MakeGenericType(t);
IList list = (IList)Activator.CreateInstance(listType);

Should do the trick.

You'll have to cast the objects when retrieving them using the IList interface, but the underlying List will enforce that only objects of type T are added to the collection.

Justin Niessner