4

I just got caught on interview question. I expected the output to be "Derived.Func(int)" but actual output was "Derived.Func(object)"

Why function with object argument was called and not function with int argument??

public void Main()
{
    //What will be written in console output?
    Derived d = new Derived();
    int i = 10;
    d.Func(i);
}

public class Derived : Base
{
    public override void Func(int x)
    {
        Console.WriteLine("Derived.Func(int)");
    }
    
    public void Func(object o)
    {
        Console.WriteLine("Derived.Func(object)");
    }
}

public class Base
{
    public virtual void Func(int x)
    {
        Console.WriteLine("Base.Func(int)");
    }
}
Roman M
  • 450
  • 1
  • 5
  • 12
  • 3
    In short - because spec somewhere says (or should say =) that it should work this way =) – Guru Stron Aug 08 '23 at 14:07
  • 4
    The correct answer (during an interview) is that code like what you show should not make it through code review. No ambiguous code (like what you show) should make it into the production branch (I do a _lot_ of maintenance work - there's a special place in hell for people who commit code like that). – Flydog57 Aug 08 '23 at 14:10
  • @Flydog57 though argument could be made that this code does not seem to be ambiguous =) – Guru Stron Aug 08 '23 at 14:17
  • 1
    Does this answer your question? [optional parameter: reversed precedence if override of overload exists](https://stackoverflow.com/questions/29392335/optional-parameter-reversed-precedence-if-override-of-overload-exists) – A.B. Aug 08 '23 at 14:24
  • 1
    That's a terrible interview question! – Eric Lippert Aug 17 '23 at 22:21
  • The answer to "what does this program do?" is best answered by *running it*, not trying to emulate the 800 pages of language specification in your head under time pressure. – Eric Lippert Aug 20 '23 at 23:43

1 Answers1

3

In short - because specification says so. If understand correctly here is the relevant part of the 12.8.9.2 Method invocations section:

The set of candidate methods is reduced to contain only methods from the most derived types: For each method C.F in the set, where C is the type in which the method F is declared, all methods declared in a base type of C are removed from the set.

For reasons why exactly - to prevent brittle/fragile base class problem as explained by Eric Lippert.

Guru Stron
  • 102,774
  • 10
  • 95
  • 132