Search code examples
c#classinheritanceclass-design

Is it possible to override a base method with a more specific (by return type) method?


I have classes like this.

public class Base{
    public virtual Base Clone(){ ...... }
}

public class Derived:Base{
    public Derived Clone(){ ...... }
    private override Base Clone(){ return Clone(); }

}

This code, of course, gives me some compile errors, one saying there are two Clone() methods in Derived class and the other saying that overriding method must be in the same accessibility level as the overridden one. Now, since the Derived.Clone() method which overrides Base.Clone() is never needed directly, I'd like to hide it with the more specific Derived.Clone() method which returns a Derived object. I know this can be done in C# with interfaces, but is it possible to do the same with classes?


Solution

  • Not in the way you show. A common approach is to introduce an extra method for the implementation:

    public class Base
    {
        public Base Clone() { return CloneImpl(); }
        protected virtual Base CloneImpl() { ... }
    }
    
    public class Derived : Base
    {
        public new Derived Clone() { ... }
        protected override Base CloneImpl() { return Clone(); }
    }
    

    This then satisfies all expectations of polymorphism, substitution, etc.