Coding curiosity 6: How to confuse a C# developer

After our first investigation to the different way in which the C# and VB compilers handle method overload resolution, this article delves a bit deeper into the same subject.

Take a quick look at the following VB code, and see if you can predict the result that it will produce.

If you guessed that the above VB code would produce the following result, you'd be in good company. I'm sure that the vast majority of VB developers would agree that this is the most intuitive result, given the slightly ambiguous circumstances. An argument of type DummyClass was passed, and the first available method that accepted a DummyClass was chosen by the overload resolution algorithm. 

Now translate the above VB code into C#, and ask a C# developer to predict what this program will produce.

Once again, the most intuitive result for most C# developers would be the same result as the VB program. Unfortunately, most C# developers would get a nasty surprise.

In spite of the fact that the class instance passed matches exactly the argument type of one of the methods of the Derived class, the other more general method is the one actually chosen by the C# overload resolution algorithm.

The reason for this is buried deep inside the C# language specification on MSDN. Section 7.4.2 states that any method marked as override is not added to the list of methods considered as candidates for the resolution of an overload. Quirks like these make the mechanical translation of code from VB to C# (or vice-versa) extremely difficult.