Reputation: 5474
While I was working with Tasks I come across this syntax:
class Program
{
static void TestMethod()
{
Console.WriteLine("Test");
}
static void Main(string[] args)
{
Task t = Task.Run(action: TestMethod); // Why this action: specifier
t.Wait();
Console.ReadKey();
}
}
If I remove the action keyword, the compiler give me an error message that say :
error CS0121: The call is ambiguous between the following methods or properties: 'System.Threading.Tasks.Task.Run(System.Action)' and 'System.Threading.Tasks.Task.Run(System.Func)'
Actually, it's weird to get this kind of message since we don't have a return Type
for the method that we pass, thus it should be treated as Action
instead of Func<>
.
I know there are many other ways to fix that error like casting to Action
or anonymous method. However, I can't understand where does this action:
come from and it's working.
Upvotes: 0
Views: 78
Reputation: 1596
This is called named arguments. It a feature of the c# language which allows to specify the arguments of a function call in an arbitrary order by specifing their name. For more information see [https://msdn.microsoft.com/en-us/library/dd264739.aspx]. In your case it makes the call of Run
unique, because only the System.Threading.Tasks.Task.Run(System.Action)
variant has a parameter called action.
Upvotes: 4
Reputation: 781
action:
is the name of the parameter. Here, you are basically telling the compiler : here is something, now I want you to put it in the parameter that's called 'action'. Since in this case the 2 methods don't have the same parameter name, the compiler is able to understand which one you want to call, hence why you get the error without it.
Side note : this can also be used to give parameters out of order when calling a function, or to specify only some optional parameter while ignoring the other ones before. Pretty cool feature sometimes.
Upvotes: 0