Resolution Overload Method and John Skeet Brain Teasers

Jon brain teasers

Spoilers will be here ...

I am looking at answer at # 1, and I must admit that I never knew what it was in case of overload resolution. But why this case. In my little mind, Derived.Foo(int) seems like a logical way to go down.

What is the logic of this design decision?

BONUS TIME!

Is this behavior the result of a C # spec, CLR implementation, or compiler?

+22
c # operator-overloading
Apr 30 '10 at 12:40
source share
5 answers

This behavior is intentional and carefully thought out. The reason is that this choice softens the influence of one of the forms of error of a fragile base class.

Read my article on this subject for more details.

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

+14
Apr 30 '10 at 15:41
source share

Here is a possible explanation:

When the compiler binds the method calls, it searches for the first place in the class that is the lowest in the inheritance chain (in this case, the Derived class). Instance methods are checked and matched. The overridden Foo method is not a Derived instance method, it is an instance method of the Base class.

The reason may be performance, as Jack30lena suggested, but it could also be the way the compiler interprets the intent of the encoder. This is a safe assumption that the developer assumes the behavior of the code in the code located at the bottom of the inheritance chain.

+1
Apr 30 '10 at 14:26
source share

This is the result of the compiler, we reviewed the IL code.

+1
Apr 30 '10 at 14:54
source share

The reason is that this is ambiguous. The compiler just has to decide for one. And someone thought that less indirect would be better (performance may be the reason). If the developer just wrote:

 ((Base)d).Foo (i); 

clear and gives the expected result.

-one
Apr 30 '10 at 14:40
source share

The reason is: performance. calling a virtual method takes a little longer. calling a delegate using a virtual method takes much more time, etc ...

see: Cost of method calls

-3
Apr 30 '10 at 14:18
source share



All Articles