Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# enhanced Method overload resolution

Tags:

c#

c#-4.0

class Base {}
class ClassA : Base {}
class ClassB : Base {}
public static class ExtensionFunctions
{
    public static bool DoSomething(this Base lhs, Base rhs)
    {
        return lhs.DoSomethingElse(rhs);
    }

    public static bool DoSomethingElse(this Base lhs, Base rhs) { return true; }
    public static bool DoSomethingElse(this ClassA lhs, ClassA rhs) { return false; }
    public static bool DoSomethingElse(this ClassA lhs, ClassB rhs) { return false; }
    public static bool DoSomethingElse(this ClassB lhs, ClassA rhs) { return false; }
    public static bool DoSomethingElse(this ClassB lhs, ClassB rhs) { return false; }
}

Given the code block above does not actually do anything but call the first DoSomethingElse method, what would be a clever approach to having the correct method call based on the real type of the parameters passed to the DoSomething method?

Is there a way I can get the method call resolved at runtime, or do I have to go with an "if typeof" style of code resolution?

like image 478
sweetfa Avatar asked Oct 07 '22 17:10

sweetfa


1 Answers

You can use the dynamic keyword:

public static bool DoSomething(this Base lhs, Base rhs)  
{
    return DoSomethingElse((dynamic)lhs, (dynamic)rhs);  
}
like image 189
Daniel Hilgarth Avatar answered Oct 10 '22 20:10

Daniel Hilgarth