0

Consider the following method:

(minimum working example - I am aware of it being effectively synchronous)

public static Task<List<int>> GetAll()
{
    var ints = new List<int>();
    ints.Add(1);
    ints.Add(2);
    ints.Add(3);

    return Task.FromResult(ints);
    // return Task<List<int>>.FromResult(ints); <-- what's the difference between this and the line before it?
}

I can use both ways, returning with Task.FromResult or Task.FromResult<TResult>. What is the difference between them? When would I use which? Why are there two possibilities that lead to the likely same result?

Update: As they are both the same - any examples where the explicitely typed one would be required?

stefan.at.kotlin
  • 15,347
  • 38
  • 147
  • 270
  • The first one is implicitly typed, the second one is explicitly typed. – Jonathon Chase Sep 09 '19 at 14:49
  • With `Task.FromResult(ints)`, `TResult` is inferred from the type of `ints` by the compiler. With `Task.FromResult>(ints)`, you've explicitly provided a type value for `TResult`, meaning that *only* `List` can be accepted as a parameter. In terms of compiler output, they are equivalent. – spender Sep 09 '19 at 14:51
  • Thanks. I added a further question to the initial one, please see above. – stefan.at.kotlin Sep 09 '19 at 14:53
  • re: the edit - if you wanted your result to be `short` or `long` for example, you'd have to be explicit as the automatic inference will be `int` only. – Tyler Lee Sep 09 '19 at 14:54
  • See [Why can't the C# constructor infer type?](https://stackoverflow.com/questions/3570167/why-cant-the-c-sharp-constructor-infer-type), and especially Eric Lippert's comments for cases where the C# compiler can't infer the types involved. – CodeCaster Sep 09 '19 at 14:57
  • @stefan.at.wpf if `GetAll` returned an `Task>` it would not compile like this. But if you changed it to `return Task.FromResult>(ints);` then it would work. So there are cases where the compiler is not able to make everything work together with implicit typing. –  Sep 09 '19 at 15:15

0 Answers0