C# - How to return a completed Task with or without a result

When using tasks you at some point come across having to return a Task without actually having a Task to return. The usual case is in a unit test where you want to stub or mock something.

Return a completed task with a result

I previously made a post on how to do this here. In short you can use Task.FromResult() to create a completed Task with a result of your choice. Below is an example:

var completedTask = Task.FromResult<string>("SomeResult");

You can either await the above (preferred) or use .Result to get the string SomeResult.

Create a completed task without a result

Sometimes you may just need to return a task to fill a contract in a method. You can do this by using Task.Completed task:

var completedTask = Task.CompletedTask;

That is all there is to it, you can also await the above if you need to.

If you are on an ancient version of .Net you can also implicitly cast a Task with a result to a regular task and return that:

Task completedTask = Task.FromResult<string>("SomeResult");

completedTask in the above will be a regular Task that is completed.

That is it!

I hope you found this helpful, please leave a comment down below if it was!