Search code examples
c#apigenericstaskfactory-pattern

Interface that supports Task or Task <TResult> in one method


I am writing an API which uses the factory pattern.

I have an interface:

public interface IAbstractProduct<TRes, TCom>
{
    Task<TRes> ExecuteAsync(TCom command);
}

Task returns TRes, but sometimes I'd like to just return Task without TResults. Is it possible to insert a TRes such that Task<TRes> = Task?

Or use some other way to make the interface IAbstractProduct handle Task and Task<TRes>?


Solution

  • No, ultimately. What you could do is:

    • for reference-types (if you can add where TRes : class), perhaps return a Task<TRes> where the result is null
    • for value-types (if you can add where TRes : struct), return a Task<TRes?>

    But: if TRes could be any type, then no: this is not possible. In that scenario, you could consider something like Task<(bool HasResult, TRes Result)> - effectively a manually constructed optional type.