0

I have class in C# with virtual method, for example:

public class Car
{
    public virtual CarModel Run()
    {
        return new CarModel();
    }
}

And second class that inherits from Car class:

public class CarFiat : Car
{
    public async override Task<CarModel> Run()
    {
        var carModel = base.Run();

        await MeasureSpeed();

        return carModel;
    }

    private async Task<string> MeasureSpeed()
    {
        return await Task.FromResult("50");
    }
}

Now I get error: Return type must be CarModel to match overridden member Car.Run() When I remove await, async and Task from Run from CarFiat class it works, but I can't call async method inside it:

//public async override Task<CarModel> Run()
public override CarModel Run()
{
    var carModel = base.Run();

    //await MeasureSpeed();

    return carModel;
}
Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
Robert
  • 2,571
  • 10
  • 63
  • 95
  • 4
    It is impossible to do it right. Can you change the base class? You could return `Task.FromResult(new CarModel());` there. – Silvermind Feb 14 '22 at 10:41
  • It doesn't look like `CarFiat.Run` needs to be asynchronous from the code you posted. – Johnathan Barclay Feb 14 '22 at 10:43
  • And why is your `MeasureSpeed` method asynchronous anyway, given that it only *really* behaves synchronously? – Jon Skeet Feb 14 '22 at 10:43
  • I posted only example, my logic is a lot of more complicated. I my real example overriden method make async request to the no-sql database and have to async, base virtual method don't have – Robert Feb 14 '22 at 10:49
  • 4
    If the method needs to be async, then the base method also needs to be async, there's no way around that without resorting to nasty hacks like trying to call async code from a sync method. – DavidG Feb 14 '22 at 10:50
  • @Silvermind and DavidG , ok I wanted to be sure if it isn't possible – Robert Feb 14 '22 at 10:54

1 Answers1

1

You will have to modify your base class to return Task<CarModel>. You can then use Task.FromResult to return synchronously in your base.

public class Car
{
    public virtual Task<CarModel> Run()
    {
        return Task.FromResult(new CarModel());
    }
}

If the above is not possible you can do sync over async, but its NOT recommend https://stackoverflow.com/a/9343733/1020941

Nisd
  • 1,068
  • 9
  • 19