3

I have a library that have a hierarchy of class as follow:

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

Now I wanted to do different thing depending on type of my object whether it is an A or a B. So I decide to go for and implement double dispatching to avoid checking type.

class ClientOfLibrary {

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

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

Now the canonical way of implementing double dispatch is to make the method MakeMeDoStuff abstract in Base and overload it in concrete class. But remember that Base, A and B are in library so I can not go and add does method freely.

Adding method extension wont work because there is no way to add an abstract extensions.

Any suggestion?

mathk
  • 7,973
  • 6
  • 45
  • 74
  • Except copying Base, A, B code in your own MyBase , MyA extends MyBase , MyB extends MyBase I don't really see an alternative. I remember we had to do something like this when I was working with c# – Heaven42 Sep 18 '14 at 12:33

1 Answers1

2

You can just use dynamic calls:

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 dispatch since introduction of dynamic, so implementing visitor pattern is unnecessary in most cases.

Athari
  • 33,702
  • 16
  • 105
  • 146
  • Thanks a lot for that, this also significantly simplifies the [Selective Visitor Pattern](http://www.educery.com/papers/patterns/visitors/selective.visitor.html)! – Tooster Jan 29 '23 at 18:31