Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a generic IList instance using reflection

I am trying to create a generic list of objects using reflection. The below code throws an error Cannot create an instance of an interface. . I could change the IList to List and it works fine, but I was wondering if there is way to get this working with an IList.

    var name = typeof (IList<T>).AssemblyQualifiedName;

    Type type = Type.GetType(name);

    var list = Activator.CreateInstance(type);
like image 385
Kumar Avatar asked Feb 04 '10 10:02

Kumar


People also ask

What is reflection in programming C#?

Reflection provides objects (of type Type) that describe assemblies, modules, and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties.

What is activator class in C#?

Activator Class in . NET 4.0. Contains methods to create types of objects locally or remotely, or obtain references to existing remote objects. ActivatorClassSample.rar. Contains methods to create types of objects locally or remotely, or obtain references to existing remote objects.


1 Answers

No, it is not possible to create an instance of an interface.

How should .NET (or rather the Activator.CreateInstance method) decide which implementation of that interface that it should instantiate ?

You can't do :

IList<int> l = new IList<int>();

either, can you ? You just cannot instantiate an interface, since an interface is merily a definition or a contract that describes which functionality a type should implement.

like image 152
Frederik Gheysels Avatar answered Oct 11 '22 09:10

Frederik Gheysels