What is the result of the following code?
using System;
class Base
{
public virtual void Foo(int x) { Console.WriteLine ("Base.Foo(int)"); }
}
class Derived : Base
{
public override void Foo(int x) { Console.WriteLine ("Derived.Foo(int)"; }
public void Foo (object o) { Console.WriteLine ("Derived.Foo(object)"); }
}
class Test
{
static void Main ()
{
Derived d = new Derived ();
int i = 10;
d.Foo (i);
}
}
The result is: Derived.Foo(object)
When the compiler chooses the overload, all functions that are declared in the derived class are chosen first, even when there is a more precise match in the base class.
When designing an inheritance hierarchy it’s wise to make sure you are not declaring more general methods in derived classes that would hide base functionality.
Resources:
- Jon Skeets Brain Teasers: http://www.yoda.arachsys.com/csharp/teasers.html