So I was playing with C# to see if it matched C++ behavior from this post: http://herbsutter.com/2013/05/22/gotw-5-solution-overriding-virtual-functions/ when I came across this very strange behavior:
public class BaseClass
{
public virtual void Foo(int i)
{
Console.WriteLine("Called Foo(int): " + i);
}
public void Foo(string i)
{
Console.WriteLine("Called Foo(string): " + i);
}
}
public class DerivedClass : BaseClass
{
public void Foo(double i)
{
Console.WriteLine("Called Foo(double): " + i);
}
}
public class OverriddenDerivedClass : BaseClass
{
public override void Foo(int i)
{
base.Foo(i);
}
public void Foo(double i)
{
Console.WriteLine("Called Foo(double): " + i);
}
}
class Program
{
static void Main(string[] args)
{
DerivedClass derived = new DerivedClass();
OverriddenDerivedClass overridedDerived = new OverriddenDerivedClass();
int i = 1;
double d = 2.0;
string s = "hi";
derived.Foo(i);
derived.Foo(d);
derived.Foo(s);
overridedDerived.Foo(i);
overridedDerived.Foo(d);
overridedDerived.Foo(s);
}
}
Output
Called Foo(double): 1
Called Foo(double): 2
Called Foo(string): hi
Called Foo(double): 1
Called Foo(double): 2
Called Foo(string): hi
So apparently it favors the implicitly converted int to double over the more specific Foo(int) from the base class. Or does it hide the Foo(int) from the base class? But then: why isn't Foo(string) hidden? Feels very inconsistent... It also does not matter if I override Foo(int) or not; the outcome is the same. Can anyone explain what's going on here?
(Yes I know that it is bad practice to overload base methods in a derived class - Liskov and all - but I still wouldn't expect that Foo(int) in OverriddenDerivedClass isn't called?!)