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?
You can use the dynamic
keyword:
public static bool DoSomething(this Base lhs, Base rhs)
{
return DoSomethingElse((dynamic)lhs, (dynamic)rhs);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With