Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Task.Factory.StartNew() overloads

I've got really simple code:

static void Main(string[] args)
{
    var task = Task.Factory.StartNew(GetInt);

    var task2 = Task.Factory.StartNew(
        () =>
        {
            return GetInt();
        });
}

static int GetInt()
{
    return 64;
}

Why do I get a compiler error for the first task? The method signatures (no params, return type is int) are equal, aren't they?

I know a solution(which is quite simple: var task = Task.Factory.StartNew<int>(GetInt);) but I'd like to know whats the problem with the code above.

like image 823
GameScripting Avatar asked Apr 05 '12 18:04

GameScripting


2 Answers

You get an ambiguous call error because the method signature is the same. Return values are not part of the signature.

Since you don't provide an explicit return type, the compiler doesn't know which to take.

Method Signature in C#

like image 190
Alex Avatar answered Sep 28 '22 06:09

Alex


Because the compiler cannot decide which of these two overloads to use:

StartNew(Action)
StartNew<TResult>(Func<TResult>)

The reason for that is that the return type is not part of the overload resolution in C# (same way as you can't have two overloads only differing in return types) and therefore the compiler cannot decide whether GetInt should be an Action or a Func<T>. Forcing to use the generic version by calling StartNew<int>(GetInt) will provide the required information.

like image 27
ChrisWue Avatar answered Sep 28 '22 06:09

ChrisWue