Why async / await allows for implicit conversion from a List to IEnumerable?
Clearly you understand why List<T>
can at least be returned as IEnumerable<T>
: simply because it implements that interface.
Also clearly, the 3rd example is doing something "extra" that the forth one isn't. As others have said, the 4th fails because of the lack of co-variance (or contra-, I can never remember which way they go!), because you are directly trying to offer an instance of Task<List<DoctorDto>>
as an instance of Task<IEnumerable<DoctorDto>>
.
The reason the 3rd passes is because await
adds a big bunch of "backing code" to get it to work as intended. This code resolves the Task<T>
into T
, such that return await Task<something>
will return the type closed in the generic Task<T>
, in this case something
.
That the method signature then returns Task<T>
and it works is again solved by the compiler, which requires Task<T>
, Task
, or void
for async methods and simply massages your T
back into a Task<T>
as part of all the background generated asyn/await continuation gubbins.
It is this added step of getting a T
from await
and needing to translate it back into a Task<T>
that gives it the space it needs to work. You are not trying to take an existing instance of a Task<U>
to satisfy a Task<T>
, you are instead creating a brand new Task<T>
, giving it a U : T
, and on construction the implicit cast occurs as you would expect (in exactly the same way as you expect IEnumerable<T> myVar = new List<T>();
to work).
Blame / thank the compiler, I often do ;-)
Just think about your types. Task<T>
is not variant, so it's not convertible to Task<U>
, even if T : U
.
However, if t
is Task<T>
, then the type of await t
is T
, and T
can be converted to U
if T : U
.
Task<T>
is simply not a covariant type.
Although List<T>
can be converted to IEnumerable<T>
, Task<List<T>>
cannot be converted to Task<IEnumerable<T>>
. And In #4, Task.FromResult(doctors)
returns Task<List<DoctorDto>>
.
In #3, we have:
return await Task.FromResult(doctors)
Which is the same as:
return await Task.FromResult<List<DoctorDto>>(doctors)
Which is the same as:
List<DoctorDto> result = await Task.FromResult<List<DoctorDto>>(doctors);
return result;
This works because List<DoctorDto>
can be converted IEnumerable<DoctorDto>
.