-3

How can I do this?

public abstract class A {

    protected abstract async Task foo(int a);

    protected async Task bar(int a) {
        await foo(a);
    }
}

public class B : A {
    public async Task foo(int a) {
        return a + 1;
    }
}

basically I want to declare a async function without a body in in the abstract class, also have another function in the abstract class use the function like it existed. But have that function defined with a body in the class that implements the abstract class.

Note: the foo in my code has something in it that uses await, so it has to be async.

Is this possible?

AustinWBryan
  • 3,249
  • 3
  • 24
  • 42
omega
  • 40,311
  • 81
  • 251
  • 474
  • I dont see how that question answers my question? – omega Aug 10 '18 at 16:30
  • @servy as much as both this and the question you linked to are in the same domain, they are not duplicates of each other. The question you linked was primarily about the compiler warning you get when you don't use await in an async function. This one is more about defining that in the first place. The accepted answer to that question won't help this user. – Sam I am says Reinstate Monica Aug 10 '18 at 16:34
  • Async is not like every other part of method declaration. You cannot force something to be async. All you can do is specify return type as `Task` – FCin Aug 10 '18 at 16:36
  • Sam I am's answer below is correct. Just get rid of the async in the abstract declaration. – Sentinel Aug 10 '18 at 16:43

2 Answers2

0

Don't make foo async in your abstract class. As long as it returns a Task you can still override it with an async implementation.

Other things you need to account for:

  • you need the override keyword on the foo function in B
  • If you want to return an int, it needs to be Task<int>
  • they either both have to be protected or both public. You can't have one protected and the other public.
-2

You are missing the override keyword:

public abstract class A {

    public abstract Task<int> foo(int a);

    protected async Task bar(int a) {
        await foo(a);
    }
}

public class B : A {
    public override async Task<int> foo(int a) {
        return a + 1;
    }
}
AustinWBryan
  • 3,249
  • 3
  • 24
  • 42
Keith Harris
  • 1,118
  • 3
  • 13
  • 25