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”.
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:
private static void TakesItem(Action item)
private static int TakesItem(Func<int> item)
public static int somefunction()
static void Main(string args)
int resultitem = TakesItem(somefunction);
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
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.