Consider this simple code:
public void Main()
{
var d = new Derived();
test(d);
}
public void test(Base parameter)
{
parameter.Validate();
}
public class Base
{
}
public class Derived : Base
{
}
public static class Validation
{
public static void Validate(this Base b)
{
Console.WriteLine("Validation for base");
}
public static void Validate(this Derived d)
{
Console.WriteLine("Validation for Derived");
}
}
When the test method is called, it will execute the Validate method which takes the base parameter, as opposed as if I had called d.Validate()
.
How can I force the test method to call the proper Validate method, without making a type test in it?
You're wanting a virtual extension method which is not supported. Extension methods are just syntactic sugar around static method calls which are bound at compile-time. You'd have to add some dynamic dispatching by looking at the run-time type to see which extension method should be called.
In your case, why not just make Validate
a virtual method of the base class?
public class Base
{
public virtual void Validate()
{
Console.WriteLine("Validation for base");
}
}
public class Derived : Base
{
public override void Validate()
{
base.Validate(); // optional
Console.WriteLine("Validation for Derived");
}
}
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