6

Was just going through a quiz online for interview prep in C#. I read this problem:

using System;

// ...

public class Program
{
    static void Main(string[] args)
    {
        Derived d = new Derived();
        int i = 10;
        d.Func(i);
    }
}

public class Base
{
    public virtual void Func(int x)
    {
        Console.WriteLine("Base.Func(int)");
    }
}

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)");
    }
}

And it says that the output should actually be Derived.Fun(Object). Can you help me to understand why it would do this? I thought it would call the Func command with the integer as the parameter.

CSDev
  • 3,177
  • 6
  • 19
  • 37
MrDaveForDays
  • 121
  • 1
  • 7
  • 4
    My answer to a question like that would be "You shouldn't write code where it's not obvious what method will be called". – juharr Jul 25 '19 at 19:17
  • @juharr: to many people it would be immediately "obvious" that `Derived.Func(int)` should be called, as that's "clearly" a better match. The C# rules for overload resolution are the most complicated part of the spec, but I imagine not all developers know this -- until they come across a case like this. – Jeroen Mostert Jul 25 '19 at 19:19
  • 2
    Also asked [here](https://stackoverflow.com/questions/52549449/why-is-method-with-object-parameter-called-instead-of-int-parameter) - dupe in and of itself – Wim Ombelets Jul 25 '19 at 19:19
  • 1
    The real answer, "why", is in the bit about the "brittle base class problem" [here](https://csharpindepth.com/Articles/Overloading). – 15ee8f99-57ff-4f92-890c-b56153 Jul 25 '19 at 19:22

0 Answers0