If I have an interface such as:
using System.Threading.Tasks;
...
public interface IFoo
{
Task doIt();
Task<bool> doItAndReturnStuff();
}
and one of the classes implementing this interface just happens to not require async methods, how can i correct override these functions?
In other words, how do I correctly return "void" and "bool" wrapped in Task objects?
For example:
public class FooHappensToNotNeedAsync : IFoo
{
public override Task doIt()
{
// If I don't return anything here, I get
// error that not all code paths return a value.
// Can I just return null?
}
public override Task<bool> doItAndReturnStuff()
{
// If I want to return true, how to I do it?
// This doesn't work:
return true;
}
}
NOTE - I can't strip the Task stuff completely because some of the classes that implement this interface are in fact asynch.
Thanks
It's not clear what you're trying to achieve, but one approach (which would look the most like "normal" code) is probably just to make them async methods anyway:
public async Task DoIt()
{
// No-op
}
public async Task<bool> DoItAndReturnStuff()
{
return true;
}
Without any await
expressions, the method will complete synchronously anyway. You'll get a warning on each method, but you could disable that just for this piece of code using a #pragma
.
Alternatively - and I guess more simply in terms of not requiring a #pragma
to disable warnings - would be to use Task.FromResult
:
public Task DoIt()
{
// Returns a Task<bool>, but that's okay - it's still a Task
return Task.FromResult(true);
}
public Task<bool> DoItAndReturnStuff()
{
return Task.FromResult(true);
}
override
as it's implementing an interface, not overriding a base class method. I only get CS0161 without the async
modifier. - Jon Skeet
return Task.Run(()=>true);
- L.B