Inheritance and Extension Method

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 a test method is called, it will execute the Validate method, which takes a base parameter, as opposed to what I called d.Validate()

.

How do I make the test method call the correct validator method without making a type test in it?

+3


source to share


1 answer


You need a virtual extension method which is not supported. Extension methods are just syntactic sugar around static method calls that are linked at compile time. You need to add dynamic dispatch by looking at the runtime type to see which extension method to call.

In your case, why not just make it a Validate

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");
    }
}

      

0


source







All Articles