Search code examples
c#inheritancepolymorphismoverriding

Why can't a deriving class override a property in its base class with a type derived from the original type?


Effectively, I'd like to understand why this is not possible in C#:

class Foo{
    public Bar Property {get;set;}
}

class Boo : Foo{
    public override Baz Property {get;set;}
}

class Bar{
    //some internal stuff
}

class Baz : Bar{
    //more stuff
}

To me, it seems like this would have pretty clearly defined behavior in most cases, so long as the Baz class doesn't hide a member from the Bar class (with new or something). The compiler would know if this was going to happen though, so it seems like a kind of non-issue.

I also understand that this can be achieved with abstract classes, but I specifically would like to get a better understanding of why this is disallowed in the case of non-abstract classes.


Solution

  • Imagine someone uses your code:

    Foo f = new Boo();
    

    As the reference is of type Foo we can only assume Property to be of type Bar. So we can also write this now:

    f.Property = new Boz(); // assuming Boz also derives from Bar
    

    which will pretty sure not be what you actually wanted.