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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace testoverloadresolution { class Program { private static void TakesItem(Action item) { } private static int TakesItem(Func<int> item) { return item(); } public static int somefunction() { return 50; } static void Main(string[] args) { int resultitem = TakesItem(somefunction); Console.WriteLine(resultitem); Console.ReadKey(); } } } </int> |
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.
Have something to say about this post? Comment!