Skip to content

Proposal: Allow covariance on return types #182

@HaloFour

Description

@HaloFour

Problem

Currently when overriding a virtual method the overriding method is required to match the signature including the return value. This prevents the overriding method from returning a more specific type which could be useful to the caller which would then not have to cast. This is a limitation imposed by the C# compiler and not a limitation of the CLR.

The closest solution to this today is to shadow the method in the derived class and have that method return the more specific type. However, the derived class cannot both shadow the method and override the method.

Proposal

Remove the limitation on the compiler and allow the overriding of methods with a covariant return type.

public class Foo {
    public virtual Foo MyMethod() {
        return this;
    }
}

public class Bar : Foo {
    // override the method, the return type can be Foo or any type deriving from Foo
    public override Bar MyMethod() {
        // do stuff here
        return (Bar)base.MyMethod(); // calling the base method still returns Foo
    }
}

...

Bar bar1 = new Bar();
Foo foo1 = bar1;
Bar bar2 = bar1.MyMethod(); // since Bar::MyMethod returns Bar no cast is required
Foo foo2 = foo1.MyMethod(); // virtually dispatches to Bar::MyMethod and returns a Bar but the apparent return type is still Foo and must be cast

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions