Improved overload resolution C# with Example



Improved overload resolution C# with Example

Following snippet shows an example of passing a method group (as opposed to a lambda) when a delegate is 
expected. Overload resolution will now resolve this instead of raising an ambiguous overload error due to the 
ability of C# 6 to check the return type of the method that was passed. 
using System; 
public class Program 
{ 
public static void Main() 
{ 
Overloaded(DoSomething); 
} 
static void Overloaded(Action action) 
{ 
Console.WriteLine("overload with action called"); 
} 
static void Overloaded(Func function) 
{ 
Console.WriteLine("overload with Func called"); 
} 
static int DoSomething() 
{ 
Console.WriteLine(0); 
return 0; 
} 
} 
Results: 
Version = 6.0 
 

Output 
overload with Func called 
View Demo 
Version = 5.0 
Error 
error CS0121: The call is ambiguous between the following methods or properties: 
'Program.Overloaded(System.Action)' and 'Program.Overloaded(System.Func)' 
C# 6 can also handle well the following case of exact matching for lambda expressions which would have resulted 
in an error in C# 5. 
using System; 
class Program 
{ 
static void Foo(Func> func) {} 
static void Foo(Func> func) {} 
static void Main() 
{ 
Foo(() => () => 7); 
} 
} 

0 Comment's

Comment Form

Submit Comment