Home > Net >  Why can you return Task<TResult> when Task is expected?
Why can you return Task<TResult> when Task is expected?

Time:01-09

As I was messing with tasks, I made a private async method that returns a random number after a delay. I had also made a public method that calls the private async method, but I had forgotten to change the return type from Task to Task<int>.

Is this just some shorthand version at work? If not, does that mean you can always return a derived class if the base class is expected?

CodePudding user response:

does that mean you can always return a derived class if the base class is expected?

Yes. All Task<T>s are Tasks, so it is always fine to convert references from the former to the later. This is true both for return values as well as parameters and other in other circumstances.

This is just normal inheritance, if this is unfamiliar to you I would suggest reading the introduction, since this is a fairly fundamental topic.

  • Related