In the following code, i have an overloaded method, one that takes a parameter of type ClazzA and the other of type ClazzB. In the code shown, the first GetDescription method (the one that takes ClazzA as a parameter) is called. I think i understand why.
My question is..is there an elegant way of having the method that takes clazzB called first if the underlying object is of type classB (without having to inspect each object and casting it to clazzB)?
public class ClazzA
{
public virtual string Descr { get { return "A"; } }
}
public class ClazzB : ClazzA
{
public override string Descr { get { return "B"; } }
}
public static class test
{
public static void Main()
{
ClazzA test = new ClazzB();
GetDecription(test);
}
public static void GetDecription(ClazzA someClazz)
{
Debug.WriteLine("I am here");
}
public static void GetDecription(ClazzB someClazz)
{
Debug.WriteLine("I want to be here");
}
}
Output: “I am here”
I really want the 2nd method to be called since ‘test’ is of type ClassB. Curerently the only two solutions i have is:
-
if (test is ClazzB)
return GetDescription( (ClazzB) test );
or
- In ClassA do pretty much the same thing…check the type and delegate to the 2nd method
Both of these require inspection of the object to determine its type
Overloads are determined at compile time. The compile time type of the reference is
ClazzAso that overload is chosen. What you are asking for is related to multiple dispatch. C# and many other languages like C++ and Java only support single dispatch (viavirtualmethods). There are a number of ways people have come up with to work around this. The purest OO way of doing this is the visitor pattern. You modify the classes to contain a method (Accept) which then passes thethisreference to a method on the visitor (Visit). This works because you override theAcceptmethod in each subclass so thatthiswill be the object’s actual type. All the visitor needs is a specific method for each subclass that you want to support (see wikipedia for more details).A sample:
Usage: