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);
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With