I have classT, implementing interfaceIBar.
I have a variable list of type List<T>.
Two questions for enhancing my understanding of the language:
-
Why doesn’t this work?
var foo = (ICollection <IBar>)list; // fails! -
How to work around it (if possible)?
Let’s say
T = Fooand there’s a second classFoo2 : IBar.Then you could continue like this:
Wham! You have a type violation at runtime, since you tried to add a
Foo2to aList<Foo>.To avoid this,
ICollection<Foo>is not a subtype ofICollection<IBar>, even thoughFoois a subtype ofIBar. The theory behind this is co- and contravariance.