Click here to Skip to main content
15,891,136 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
In a base class, I am trying to create a default implementation for a function returning Task<string>. I can work out how to do this 'long-hand' but I can't help thinking there is a neater way of writing this.

This is my current version:

protected virtual async Task<string> MyFunction()
{
    await Task.Delay( 0 );
    return "";
}


What I have tried:

I thought I might be able to use TaskCompletionSource or Task.FromResult() but don't seem to be able to work out a syntax for these. When using the latter, I can't get round a message that tells me I should be returning a string, not a Task<string>.
Posted
Updated 1-Oct-19 1:18am

You can just return String.Empty without doing the await. Of course, that would make the method synchronous (because there's no await statement), but I don't see that as a bad thing if it's merely a default implementation.
 
Share this answer
 
v2
Comments
Patrick Skelton 1-Oct-19 7:23am    
Doesn't that mean you are forever stuck with the compiler warning telling you that the task will complete synchronously?
#realJSOP 1-Oct-19 7:27am    
Not if you turn off that warning for that method:

#pragma warning disable CS1633,CS1998
public async Task<string>....
{
}
#pragma warning restore CS1633,CS1998
Patrick Skelton 1-Oct-19 7:30am    
Not fond of turning off warnings (since in my case, the warning is usually right and I've got my brain in neutral), but thanks for the reply.
#realJSOP 1-Oct-19 7:36am    
You can do it around just the offending method (I cahnged my reply to illustrate). Of course, you can put await in the method and be done with it.
#realJSOP 1-Oct-19 7:37am    
And, the language gives you the #pramga directive just for situations like this. I don't use them either unless necessary. In this case, it's a do-nothing default implementation of a method. It ain't gonna hurt anything...
Simple - just remove the async keyword:
C#
protected virtual Task<string> MyFunction()
{
    return Task.FromResult(string.Empty);
}
If your task completes synchronously most of the time, you might want to consider using ValueTask instead.

Understanding the Whys, Whats, and Whens of ValueTask | .NET Blog[^]
 
Share this answer
 
v2
Comments
Patrick Skelton 1-Oct-19 7:24am    
Wasn't aware of ValueTask at all, so I've learnt two things! Thank you, Richard.
#realJSOP 1-Oct-19 7:54am    
Yep, this is the answer. My approach doesn't inherit well. At all. :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900