Why instance of IList trows exception ?

02/09/2009 - 19:33 von Milan | Report spam
Hi all,

I have problem instanting object, using reflection, of type IList<A> so
following code throws exception:

class A{}

//...and in main ()

A obj_a = new A();

Type genericType = typeof( IList<> );
Type[] parameters = { obj_a.GetType() };

Type closedType = genericType.MakeGenericType(parameters); //reckognize type
correct {System.Collections.Generic.IList`1[Reflection.A]}

object newObject = Activator.CreateInstance(closedType); //Throws exception
! Why ?

Why exception is thrown when type is reckognized correctly ? But if the line:

Type genericType = typeof( IList<> );

is replaced with the line:

Type genericType = typeof( List<> );

than it works...so why Interface is problem for the function CreateInstance ?
How I can create object of type IList<T> dinamicaly ?


Lesen sie die antworten

#1 Michael Huber
02/09/2009 - 19:44 | Warnen spam
An interface only defines Methods and Properties a class must
Because of that it is not possible to create an instance of an
interface, but you can create an instance of a class that implements a

In your case, you just have to create an instance of List<T>.

Ähnliche fragen