Casting a List<T> (where T : IBar) to ICollection<IBar> fails-Collection of common programming errors
Why doesn’t this work?:
var foo = (ICollection )list;
Let’s say T = Foo and there’s a second class Foo2 : IBar.
Then you could continue like this:
var foolist = (ICollection )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.
To avoid this, ICollection is not a subtype of ICollection, even though Foo is a subtype of IBar. The theory behind this is co- and contravariance.