You can infer the task's generic argument:
public async Task<TTaskArg> RunThisFunction<TTaskArg>(Func<Task<TTaskArg>> func)
{
return await func();
}
You can place it as an overload of your existing method, and the compiler will choose the correct one based on the inferred type.
Try it online
Note: While I haven't used the async
keyword in my runnable example, that's because my code is essentially synchronous. In practice, you will probably want to use the async
and await
keywords as above.
If you wish to display a compiler warning, you could add the [Obsolete]
attribute, for example:
[Obsolete("Please do not use tasks with a generic parameter.")]
public async Task<TTaskArg> RunThisFunction<TTaskArg>(Func<Task<TTaskArg>> func)
{
return await func();
}
And perhaps (if you need it) you could throw an InvalidOperationException
from within the method if you want to prevent its (successful) use at runtime too.
As Alexei said, you could also enable "warnings as errors" for the obsolete warning (CS0612). See here for instructions on how to do that. Remember that you need to use CS0612 and not NU1605 though.