Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 662
Somebody Please Help me Avatar asked Oct 31 '22 01:10

Somebody Please Help me


1 Answers

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");
    }
}
like image 200
D Stanley Avatar answered Nov 15 '22 04:11

D Stanley