Question

I have an abstract class MyAbstractDoerClass which has an abstract method called DoItAsync as follow:

public class MyAbtractDoerClass
{
    public abstract Task DoItAsync();
}

It also has a couple of derived classes PainterClass and EraserClass:

public class PainterClass : MyAbtractDoerClass
{
    public override async Task DoItAsync();
}

public class EraserClass : MyAbtractDoerClass
{
    public override async Task DoItAsync();
}

Finally, there is a Factory method that returns an instance of any of these two classes. The signature is something like this:

public MyAbstractClass Factory(string doerType)

Now, my code looks like this:

var doer = Factory("painter");
await doer.DoItAsync();  // <--- here is the problem.

Given that MyAbstractClass.DoItAsync method is an abstract one, it cannot be marked as async and because of that I cannot use the await keyword in the API client. That makes my API usability seem very bad. I suspect there is something wrong in my design, some concept that I didn't fully understand but I don't know what.

What is wrong with my code?

Update

This is the error that I got in VS: enter image description here

And this is the method's signature in the abstract class:

enter image description here

Was it helpful?

Solution

You certainly can do this:

await doer.DoItAsync();

The key point of understanding is that types are awaitable, not methods. You can do await doer.DoItAsync() because DoItAsync returns a Task, not because DoItAsync is async. I explain this more in my async intro post.

Put another way, that code is exactly the same as:

Task temp = doer.DoItAsync();
await temp;

I have an "async OOP" series on my blog; one of the posts covers async in inheritance scenarios.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top