Search code examples
c#ilistgettype

Using Type.GetType(string) in IList<T>


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.


Solution

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