Skip to content

Proposal: Virtual arguments in methods #176

@mariusGundersen

Description

@mariusGundersen

Currently the virtual keyword can be used to mark a method as being virtual, so that calling the method on an object with the interface type will call it on the actual type:

ISomething something = GetOneImplementationOfISomething();
something.DoIt();//this will call the correct DoIt based on the actual type of something

Unfortunately the same thing cannot be done with a method that gets a parameter, for example:

private void DoIt(ISomething something){
  //this is the only one that gets called
}
private void DoIt(SomethingImplementation something){
  //this one is never called
}

ISomething something = GetOneImplementationOfISomething();
DoIt(something);

This means that extension methods can't be virtual today.

I therefore propose that the virtual keyword can be declared on one of the arguments to a method if the method isn't marked as virtual (thereby restricting it to single dispatch and not multiple dispatch). For example:

public static class Extensions
{
    public static string NameOf(virtual this ISomething something)
    {
        return "interface";
    }
    public static string NameOf(virtual this SomethingOne something)
    {
        return "one";
    }
    public static string NameOf(virtual this SomethingTwo something)
    {
        return "two";
    }
}
//...
var s = GetSomething();
s.NameOf();
//or 
Extensions.NameOf(s);

This is currently possible today using dynamic, which means that, afaict, this proposal is only syntax sugar on top what is currently possible.

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