Casting a List<T> (where T : IBar) to ICollection<IBar> fails
-
05-02-2021 - |
Question
I have class
T
, implementing interface
IBar
.
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)?
La solution
Why doesn't this work?:
var foo = (ICollection <IBar>)list;
Let's say T = Foo
and there's a second class Foo2 : IBar
.
Then you could continue like this:
var foolist = (ICollection <IBar>)list;
foolist.Add(new Foo2()); // compiles, since Foo2 also implements IBar
Wham! You have a type violation at runtime, since you tried to add a Foo2
to a List<Foo>
.
To avoid this, ICollection<Foo>
is not a subtype of ICollection<IBar>
, even though Foo
is a subtype of IBar
. The theory behind this is co- and contravariance.
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow