Search code examples
c#asynchronouslanguage-designreturn-type

On async return type


Wondering why we should specify that async method does return Task object.

Specifying it seems redundant with the async keyword plus it is confusion since you do not really create the Task object.

As I understand the compiler does emit the necessary code for Task object creation (Whether on a await call or wrapping the return with a new Task.).

I don't really like the inconsistency between the declare type and the return Type.


Solution

  • I have a blog post that describes the reasoning in detail. Inferring the return type was considered but they decided not to.

    With the explicit return type, the async keyword is more of an implementation detail. There are two reasons to have the explicit return type:

    • The method signature is consistent (it's the same at the point of declaration as when observed using IntelliSense or reflection).
    • There is a difference between async void and async Task. With an inferred return type, there's no clear way to define an async void method.