Search code examples
c#oopinheritancederived-classbase-class

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


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

public static Task GetRandomNumber()
{
  return GetRandomNumberAsync();
}

private static async Task<int> GetRandomNumberAsync()
{
  await Task.Delay(2000);
  var rnd = new Random();
  return rnd.Next();
}

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?


Solution

  • 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.