How to create double submissions using extensions

I have a library that has a class hierarchy:

class Base {}
class A : Base {}
class B : Base {}

      

Now I wanted to do another thing depending on the type of my object, be it A or B. So I decided to go and implement double dispatch to avoid type checking.

class ClientOfLibrary {

    public DoStuff(Base anObject)
    {
       anObject.MakeMeDoStuff(this);
    }

    private void DoStuffForanA(A anA);
    private void DoStuffForaB(B aB);
}

      

Now the canonical way to implement double dispatch is to MakeMeDoStuff

abstract the method in Base

and overload it in the concrete class. But remember that Base

, A

and B

are in the library, so I can't go and add the method freely.

Adding a method extension does not work because there is no way to add abstract extensions.

Any suggestion?

+3


source to share


1 answer


You can just use calls dynamic

:

class ClientOfLibrary {

    public DoStuff(Base o)
    {
       DoStuffInternal((dynamic)o);
    }

    private void DoStuffInternal(A anA) { }
    private void DoStuffInternal(B aB) { }
    private void DoStuffInternal(Base o) { /* unsupported type */ }
}

      



C # natively supports multiple dispatches from the moment of input dynamic

, so injecting the visitor pattern is not required in most cases.

+2


source







All Articles