Advanced C # Method Overload Resolution

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 that the code block described above actually does nothing but call the first DoSomethingElse method, would it be wise to correctly call the method based on the real type of parameters passed to the DoSomething method?

Is there a way to force the method call to resolve at run time, or do I need to go with the type “if type” to resolve the code?

+5
source share
1 answer

You can use the keyword dynamic:

public static bool DoSomething(this Base lhs, Base rhs)  
{
    return DoSomethingElse((dynamic)lhs, (dynamic)rhs);  
}
+4
source

All Articles