0

If I have an abstract class with an async method I can override this method in an implementing class. However, what would be the most optimal way of overriding this method? Should the base method be awaited in the implementing class, or should it just return the original Task?

public abstract class Animal {
    public async Task<int> DoSomething() {
        return await DoSomethingElse();
    }
}

public class Giraffe : Animal {

    // Awaiting the base method?
    public new async Task<int> DoSomething() {
        return await base.DoSomething();
    }

    // Or returning the base method's Task?
    public new Task<int> DoSomething() {
        return base.DoSomething();
    }
}
TheHvidsten
  • 4,028
  • 3
  • 29
  • 62
  • 7
    See "[Eliding Async and Await](https://blog.stephencleary.com/2016/12/eliding-async-await.html)" by the one and only Stephen C. – Fildor Jul 05 '21 at 12:38
  • 1
    You are talking about "overriding", but the posted code demonstrates hiding, by using the `new` keyword. [Which is which](https://stackoverflow.com/questions/1399127/difference-between-new-and-override)? – Theodor Zoulias Jul 05 '21 at 13:25
  • 1
    If you just invoke the base implementation and return its result (awaited or not) you should not even implement / override it. In general if a method returning a task is a one-liner it shouldn't be `async`. The caller can still await it if he decides to. If you want your base method to be overridable, mark it as `virtual`. – lidqy Jul 05 '21 at 13:31

0 Answers0