Can I Override with derived types?

Luis Filipe picture Luis Filipe · Oct 1, 2008 · Viewed 29.8k times · Source

As far as i know it is not possible to do the following in C# 2.0

public class Father
{
    public virtual Father SomePropertyName
    {
        get
        {
            return this;
        }
    }
}

public class Child : Father
{
    public override Child SomePropertyName
    {
        get
        {
            return this;
        }
    }
}

I workaround the problem by creating the property in the derived class as "new", but of course that is not polymorphic.

public new Child SomePropertyName

Is there any solution in 2.0? What about any features in 3.5 that address this matter?

Answer

Marc Gravell picture Marc Gravell · Oct 1, 2008

You can re-declare (new), but you can't re-declare and override at the same time (with the same name). One option is to use a protected method to hide the detail - this allows both polymorphism and hiding at the same time:

public class Father
{
    public Father SomePropertyName
    {
        get {
            return SomePropertyImpl();
        }
    }
    protected virtual Father SomePropertyImpl()
    {
        // base-class version
    }
}

public class Child : Father
{
    public new Child SomePropertyName
    {
        get
        { // since we know our local SomePropertyImpl actually returns a Child
            return (Child)SomePropertyImpl();
        }
    }
    protected override Father SomePropertyImpl()
    {
        // do something different, might return a Child
        // but typed as Father for the return
    }
}