Question

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?

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top