-2

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?

so_as
  • 41
  • 6
  • 5
    because a `Task` object is a subclass of Task. – jazb Jan 09 '23 at 07:31
  • 2
    "If not does that mean you can always return a derived class if the base class is expected?" Yes. That's just normal inheritance, in the way that it's worked since C# 1.0. – Jon Skeet Jan 09 '23 at 07:34
  • See also: ["LSP"](https://en.wikipedia.org/wiki/Liskov_substitution_principle) – Fildor Jan 09 '23 at 07:41

1 Answers1

0

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.

JonasH
  • 28,608
  • 2
  • 10
  • 23
  • Is it a language feature that `X` always has `X` as a base class , or is this just part of the definition to `Task` ? – M.M Jan 12 '23 at 23:12
  • @M.M that is just the definition of `Task`. Take a look at [`List`](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1?view=net-7.0),while it inherits from `IList` and `IList`, it does not inherit from `List` – JonasH Jan 13 '23 at 07:58