1

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)?

Konrad Morawski
  • 8,307
  • 7
  • 53
  • 91

1 Answers1

5

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.

Heinzi
  • 167,459
  • 57
  • 363
  • 519