Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Optional Async for Interface

I have two Interfaces:

interface ICommandAsync : ICommand
{
    new Task Run(params string[] args);
}

and

interface ICommand
{
    string Name { get; }
    string Desc { get; }
    void Run(params string[] args);
}

'CommandWeather' does not implement interface member 'ICommand.Run(params string[])'. 'CommandWeather.Run(params string[])' cannot implement 'ICommand.Run(params string[])' because it does not have the matching return type of 'void'.

Here is CommandWeather, or the offending class:

class CommandWeather : ICommandAsync
{
    public async Task Run(params string[] args)
    {
        //...
    }
}

My question is this: How can I make an interface that is optionally async? I need the methods to have the same name since they will both be called with Run(), and only a few implementations of ICommand or ICommandAsync actually need to use async. This means that I get green lines for having a synchronous async method.

like image 232
Orion31 Avatar asked Aug 13 '26 10:08

Orion31


1 Answers

Implement at least one of them explicitly.

class CommandWeather : ICommandAsync
{
    public async Task Run(params string[] args)
    {
        //...
    }

    // Explicitly implement ICommand.Run
    void ICommand.Run(params string[] args)
    {
        //...
    }
}

This is how IEnumerator.Current has to be implemented since IEnumerator<T>.Current is declared with new and is of type T rather than object.

@Johnny makes a good point, though, that async methods usually have the Async suffix. That would also solve the problem.

like image 164
madreflection Avatar answered Aug 14 '26 23:08

madreflection



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!