imgen
imgen

Reputation: 3133

Overload resolution and async await

Below code gives error CS0121,

The call is ambiguous between the following methods or properties: 'RunTask(System.Func<System.Threading.Tasks.Task>)' and 'RunTask(System.Action)'

static void RunTask(Func<Task> intTask)
{
}

static void RunTask(Action voidTask)
{
}

static async Task DoAsyncTask()
{
    await Task.Delay(500);
}

public static void Main(string[] args)
{
    var asyncTask = new Func<Task>(DoAsyncTask);
    RunTask(DoAsyncTask);
}

But below code can compile

static void RunTask(Func<Task> intTask)
{
}

static void RunTask(Action voidTask)
{
}

static async Task DoAsyncTask()
{
    await Task.Delay(500);
}

public static void Main(string[] args)
{
    var asyncTask = new Func<Task>(DoAsyncTask);
    RunTask(asyncTask);
}

Why so?

Upvotes: 2

Views: 516

Answers (1)

Moeri
Moeri

Reputation: 9304

The C# compiler does not take return type of a delegate into account when trying to decide the best overloaded method that takes a delegate.

Also see this question

Upvotes: 3

Related Questions