C#

Overloaded Inheritance in C#

class Foo {
    public void Who( int i ) {
        Console.Write("Foo");
    }
}

class Bar : Foo {
    public void Who( double d ) {
        Console.Write("Bar");
    }
}

var bar = new Bar();
bar.Who( (int) 1 );
//Outputs "Bar" to the Console

Why does the compiler use the double version of the method when we passed an integer?

The answer is like a super bowl, it comes in two halves.

  1. There is an implicit conversion from double to integer. This makes Who() defined in Bar good enough for the compiler, or as the reference docs below call an applicable method.
  2. The compiler won’t normally look deeper into the inheritance chain if an applicable method can be found. This was done to combat the brittle base class problem found in many programming languages.

Further reading can be found at these MSDN references:
https://blogs.msdn.microsoft.com/ericlippert/2007/09/04/future-breaking-changes-part-three/
https://msdn.microsoft.com/en-us/library/aa691356(v=vs.71).aspx

Leave a Reply

Your email address will not be published. Required fields are marked *