Question

I found in the book about programming asynchronous applications the following code:

public static double ReadDataFromIO() {
    // We are simulating an I/O by putting the current thread to sleep.
    Thread.Sleep(2000);
    return 10d;
}

public static Task<double> ReadDataFromIOAsync() {
    return Task.Run(new Func<double>(ReadDataFromIO));
}

This code compiles without errors and works great. However I wanted to check which overloaded method of Task.Run (MSDN - Task.Run) is used here and didn't find any.

Moreover Visual Studio indicates that:

Task.Run<double>(Func<double> function)

is used.

How is it possible?

Was it helpful?

Solution

If you mean the silent <double> - that is generic parameter inference, and it happens routinely in C#. Basically, if you don't specify any generic type parameters, and if there isn't an exact non-generic match, then the compiler will attempt to deduce the parameters on your behalf, considering all of the available overloads. In this case, the fact that it knows (from static analysis) that Func<double> returns double allows it to deduce that the most applicable option would be <double>, using the Task<TResult> Task.Run<TResult>(Func<TResult>) overload.

If it cannot deduce all of the generic parameters, or if it cannot find a suitable set of unambiguous options for a suitable overload, it will simply give up and tell you to specify them yourself.

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