0

Simple hierarchy, 3 levels and with a shared/single dependency to a class with overloaded methods that differ only by type signature:

enter image description here

When viewed in a debugger, the type of 'this' in Derived.Bar is the instantiated/concrete Double-Derived.

The below works as expected ONLY because of the (dynamic) cast. Remove it and you'll see that the overload resolution uses the calling class rather than the concrete class.

Curious if there's a 'purer' way of it working as expected without the performance hit of DLR (or some other reflection-based alternative):

public class PolymorphicConsumer
{
    public void Foo(Base caller)
    {
        Console.WriteLine("Its all about the base.");
    }

    public void Foo(Derived caller)
    {
        Console.WriteLine("Its all about the Derived.");
    }

    public void Foo(DoubleDerived caller)
    {
        Console.WriteLine("Its all about the Double-Derived.");
    }

}

public abstract class Base
{
    protected PolymorphicConsumer _dep;
    public Base (PolymorphicConsumer dep)
    {
        _dep = dep;
    }
    public virtual void Bar()
    {
        // No impl.
    }

}

public class Derived : Base
{
    public Derived(PolymorphicConsumer dep):base(dep)
    { }

    public override void Bar()
    {
        _dep.Foo((dynamic)this);            
    }
}

public class DoubleDerived : Derived
{
    public DoubleDerived(PolymorphicConsumer dep):base(dep)
    { }
}

class Program
{
    static void Main(string[] args)
    {
        var dd = new DoubleDerived(new PolymorphicConsumer());

        dd.Bar();

        Console.ReadKey();
    }
}
StephenS
  • 23
  • 7
  • 1
    Possible duplicate of [Double dispatch in C#?](https://stackoverflow.com/questions/42587/double-dispatch-in-c) – dsolimano Nov 27 '17 at 14:18
  • Having that kind of overload in itself feels like a bit of a design smell. I'm curious about the actual use case. – Rotem Nov 27 '17 at 14:18
  • There's conflicting advice on the design: https://lostechies.com/derekgreer/2010/04/19/double-dispatch-is-a-code-smell/ **vs** https://lostechies.com/jimmybogard/2010/03/30/strengthening-your-domain-the-double-dispatch-pattern/ Thanks @dsolimano for the link, which at least one of these is sourced from. Will close as a dupe... – StephenS Nov 27 '17 at 17:15

0 Answers0