Creating a shared instance of IList using reflection

I am trying to create a general list of objects using reflection. The following code displays the error message Unable to instantiate interface. . I could change IList to List, and it works fine, but I was wondering if there is a way to get this to work with IList.

var name = typeof (IList<T>).AssemblyQualifiedName; Type type = Type.GetType(name); var list = Activator.CreateInstance(type); 
+6
reflection c #
source share
8 answers

you will need to set a specific class so that if you do

 var type = Type.GetType(typeof (List<T>).AssemblyQualifiedName); var list = (Ilist<T>)Activator.CreateInstance(type); 

you will be successful (if you, of course, set the correct value for T).

+7
source share

No, it is not possible to instantiate an interface.

How should .NET (or, rather, the Activator.CreateInstance method) decide which implementation of this interface it should create?

You can not:

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

is not it? You simply cannot instantiate an interface, because an interface is just a definition or contract that describes what kind of functionality a type should implement.

+9
source share

Activator.CreateInstance method calls the default constructor to create an instance of the type passed as a parameter. This type should not be abstract, but not an interface and have a default constructor for this function to succeed.

+6
source share

I don’t think you can make this work because you don’t know what type of object you need to create.

You will have the same problem with an abstract class.

+3
source share

Well no, this is impossible. The error message is crystal clear. You cannot create an instance of an interface.

How does he know which particular class you need? Often many classes implement the same interface. Should he just pick one at random ?; -)

This has nothing to do with thinking, since you also cannot “instantiate” the interface. Use only objects that implement the interface, and then pass a link to the interface.

+2
source share

Obviously, you cannot initiate an object of type IList<T> directly, because it is an interface type.

You should try to initialize List<T> and then possibly return it as IList<T> .

+2
source share
 IList<T> Create<T>() { Type baseListType = typeof(List<>); Type listType = baseListType.MakeGenericType(typeof(T)); return Activator.CreateInstance(listType) as IList<T>; } 
+2
source share

Well, you CAN initialize the interface in C #. But only if you really tell how to do it.

Take a look at http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.coclassattribute.aspx and http://blogs.msdn.com/brada/archive/2004/10/10/240523.aspx

In your case, however, it seems that you misunderstood how the interfaces work.

Just create a list and then return IList <T> and your calling code does not care that you are actually using List <T>.

0
source share

All Articles