Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method overloads resolution and Jon Skeet's Brain Teasers

Tags:

Jon's Brain Teasers

Here Be Spoilers...

I'm looking at the answer to #1, and I must admit I never knew this was the case in overload resolution. But why is this the case. In my tiny mind Derived.Foo(int) seems like the logical route to go down.

What is the logic behind this design decision?

BONUS TIME!

Is this behaviour a result of the C# specification, the CLR implementation, or the Compiler?

like image 979
gingerbreadboy Avatar asked Apr 30 '10 12:04

gingerbreadboy


2 Answers

This behaviour is deliberate and carefully designed. The reason is because this choice mitigates the impact of one form of the Brittle Base Class Failure.

Read my article on the subject for more details.

http://blogs.msdn.com/ericlippert/archive/2007/09/04/future-breaking-changes-part-three.aspx

like image 195
Eric Lippert Avatar answered Oct 05 '22 04:10

Eric Lippert


Here is a possible explanation:

When the compiler links the method calls, the first place it looks in in the class that is lowest in the inheritance chain (in this case the Derived class). It's instance methods are checked and matched. The overridden method Foo is not an instance method of Derived, it is an instance method of the Base class.

The reason why could be performance, as Jack30lena proposed, but it could also be how the compiler interprets the coder's intention. It's a safe assumption that the developer's intended code behavior lies in the code at the bottom of the inheritance chain.

like image 45
Audie Avatar answered Oct 05 '22 03:10

Audie