Why an inherited interface can’t be converted to its base interface in generic context?

Let’s have a play with your types and call them something different.

public interface IFruit { }

public abstract class BowlOf<Fruit> where Fruit : IFruit
{
    public void Add(Fruit fruit) { }
}

public class Apple : IFruit { }

public class BowlOfApples : BowlOf<Apple> { }

Now, with that – which is pretty much just a rename of the types (but changing public interface ChildInterface : BaseInterface {} to public class Apple : IFruit { }) then we create the following issue.

Let’s say I have public class Banana : IFruit { } also and let’s assume that the following is legal:

BowlOf<IFruit> c = new BowlOfApples();

Then I am perfectly fine to call c.Add(new Banana()). What!?! You can’t add a banana to a bowl of apples.

And that’s why the compiler is complaining when you try to do AbstractClass<BaseInterface> c = new ConcreteClass();.

Leave a Comment