Essential C# C# 6.0 Features  Suggest an edit

Improved overload resolution

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<int> function)
    {
       Console.WriteLine("overload with Func<int> called");
    }

    static int DoSomething()
    {
        Console.WriteLine(0);
        return 0;
    }
}

Results:

Output

overload with Func called

View Demo

In C# 5.0 or earlier, we would get an 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<long>> func) {}
    static void Foo(Func<Func<int>> func) {}

    static void Main()
    {
        Foo(() => () => 7);
    }
}

Table Of Contents
22 Enum
25 GUID
71 C# 6.0 Features
107 Stream
108 Timers
  ↑ ↓ to navigate     ↵ to select     Esc to close