Menu

C# 6 Features: Improved Overload Resolution

June 24, 2015 - .NET, C#, Programming

This is part of a series of posts covering new C# 6 features. Currently there are posts covering the following:
String Interpolation
Expression-bodied Members
Improved Overload resolution
The Null Conditional operator
Auto-Property Initializers

I previously posted about the new Expression-bodied Members and String Interpolation features of C# 6.0. There are quite a few features to cover, but today I think I’ll cover one that perhaps get a bit less coverage overall. This feature is listed as “Improved Overload resolution”.

So what is it?

While I’m perhaps not aware of the full breadth of the revisions made to overload resolution, one of the definite improvements was that C# 6.0 will now take into account the return type of method-group arguments. It is not really immediately obvious what this changes, so an example really works best. Take the following code:

In Visual Studio 2015, this code fails to compile. The compiler issues an Error- “The call is ambiguous between the following methods or properties: ‘testoverloadresolution.TakesItem(System.Action)’ and ‘testoverloadresolution.TakesItem(System.Func<int>)’ There is also an error that somefunction has the wrong return type, and that the void cannot be implicitly converted to int. In C# 6, however, this compiles without issue.

Basically, in the C# 5.0 case, when we called the TakesItem function, the compiler would try to find the appropriate method to match the usage- however, it wasn’t taking the return type of the somefunction argument into account when matching the signature. As a result, Action and Func become indistinguishable to the compiler. C# 6 however how includes return type as part of function overload resolution, which allows it to unambiguously find the TakesItem(Func) matches the usage.

Realistically, it will prevent these sorts of errors and reduce the need to make a “fake” lambda in order to make return type be considered. A small revision but one I think should not be overshadowed too much by some of the more heavyweight and easier to demonstrate improvements such as those that I’ve already discussed.

Have something to say about this post? Comment!