user3538345
user3538345

Reputation:

Compiler picking the wrong overload

Okay I have a derived class that has an overload to a method that's on my base class. I call what I think would match the method signature of the base class but instead my derived classes implementation is called. (The code below always prints out "MyDerived") Why is this?

    public class MyBase
    {
        public void DoSomething(int a)
        {
            Console.WriteLine("MyBase");
        }
    }

    public class MyDerived : MyBase
    {
        public void DoSomething(long a)
        {
            Console.WriteLine("MyDerived");
        }
    }


Main()
{
    MyDerived d = new MyDerived();
    d.DoSomething((int)5);
}

Upvotes: 6

Views: 378

Answers (2)

Eric Lippert
Eric Lippert

Reputation: 660407

The behaviour you describe is correct. Many people consider it to be counterintuitive but it is carefully designed to prevent a brittle base class failure.

See my article on the subject for more details.

https://learn.microsoft.com/en-us/archive/blogs/ericlippert/future-breaking-changes-part-three

Upvotes: 5

Jason Roell
Jason Roell

Reputation: 6819

Most people assume the DoSomething(int) overload on the base class is a better match than the DoSomething(long) overload.

However, since the variable is a derived type, that version of DoSomething will be called. The .NET runtime always favors the most-derived compile-time type.

If it finds a method signature that will work on the derived type it will use that before moving to any of the base class methods. In general, you should avoid overloading methods defined in base classes.

Upvotes: 5

Related Questions