Skip to content

Allow overrides with more specialized return types #2

Description

@kingces95

Proposal

Allow overrides with more specialized return types.

For example, I expect the CLR to allow the addition of a virtual method MethodBase GetGenericMethodDefinition() on MethodBase to be overriden by the existing MethodInfo GetGenericMethodDefinition() on the derived class MethodInfo even though the return type of the override is more specialized (see https://github.com/dotnet/corefx/issues/23763). In actuality, the signatures of virtual overrides must match exactly.

For example, I expect this this fiddle to compile (and run) but actually fails with compiler error CS0508 'MethodInfo.GetGenericTypeDefinition()': return type must be 'MethodBase' to match overridden member 'MethodBase.GetGenericTypeDefinition()'.

public class MethodBase {
    public virtual MethodBase GetGenericTypeDefinition() => null;
}

public class MethodInfo : MethodBase {
    public override MethodInfo GetGenericTypeDefinition() => null;
}

Rational

Java does it. Why haven't we?

CSharp Team On-board

See dotnet/roslyn#357
See https://github.com/dotnet/csharplang/blob/master/proposals/covariant-returns.md
See http://flylib.com/books/en/2.663.1.64/1/
See https://www.red-gate.com/simple-talk/blogs/implementing-method-override-covariance-on-c-part-2/

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions