Skip to main content

How to Return a Finished ValueTask with ValueTask.FromResult in C#

· 6 min read
Jagdish Kumawat
Founder @ Dewiride

Some methods and lambdas have to return a ValueTask<T>, yet they already have the answer. ValueTask.FromResult(answer) wraps it in a ValueTask<T> that has already finished, with no async and no await.

Microsoft's reference: Creates a ValueTask<TResult> that's completed successfully with the specified result. And on the type it returns: Provides a value type that wraps a Task<TResult> and a TResult, only one of which is used.

Results that are ready at once are where a ValueTask helps. The reference notes that a ValueTask<TResult> can help avoid an allocation in the case where the successful result is available synchronously.

Syntax​

Syntax
ValueTask<TResult> <task> = ValueTask.FromResult(<value>);
ValueTask<TResult> <task> = ValueTask.FromResult<TResult>(<value>);
PartWhat it is
<value>The result the finished ValueTask holds
TResultThe result's type. C# works it out from <value>, unless you write it in angle brackets
<task>A ValueTask<TResult> that has already finished. await gives <value> back

The Example​

A console app called ValueTaskFromResult has a method that counts the letters of a word and a lambda that squares a number. Both must return a ValueTask<int>, and both have the answer at once.

Prerequisites​

  • The .NET 10 SDK. dotnet --version prints a version that starts with 10.0.

Step 1: Create a Console App​

Terminal
dotnet new console -n ValueTaskFromResult
cd ValueTaskFromResult
Output
The template "Console App" was created successfully.

Processing post-creation actions...
Restoring /Users/you/source/ValueTaskFromResult/ValueTaskFromResult.csproj:
Determining projects to restore...
Restored /Users/you/source/ValueTaskFromResult/ValueTaskFromResult.csproj (in 45 ms).
Restore succeeded.

dotnet new console -n ValueTaskFromResult creates a folder named ValueTaskFromResult with a project file and a Program.cs, and cd moves into it. Everything this example uses is part of .NET, so there's no package to add. Open the folder in VS Code, or ValueTaskFromResult.csproj in Visual Studio.

Step 2: Write the Code​

Replace everything in Program.cs. First the call to the method:

Program.cs (the call)
// A finished ValueTask<int>, made without async.
ValueTask<int> letters = CountLettersAsync("banana");
Console.WriteLine($"Finished already: {letters.IsCompletedSuccessfully}");
Console.WriteLine($"Letters in banana: {await letters}");
  • CountLettersAsync("banana") returns a ValueTask<int>.
  • IsCompletedSuccessfully says whether it has finished without an error. The reference: Gets a value that indicates whether this object represents a successfully completed operation.
  • await letters gives the result.

Then the lambda:

Program.cs (the lambda)
// A lambda that must return a ValueTask<int>.
Func<int, ValueTask<int>> square = number => ValueTask.FromResult(number * number);
Console.WriteLine($"7 squared: {await square(7)}");

Func<int, ValueTask<int>> is a function that takes an int and returns a ValueTask<int>. The lambda works out the square and wraps it with ValueTask.FromResult.

Then the method:

Program.cs (the method)
// The method must return a ValueTask<int>, but it has the answer at once.
static ValueTask<int> CountLettersAsync(string word)
{
return ValueTask.FromResult(word.Length);
}

The method isn't async. It counts the letters with word.Length and returns the count with ValueTask.FromResult.

Step 3: Run It​

Run it in VS Code's terminal, or press Ctrl+F5 in Visual Studio:

Terminal
dotnet run
Output
Finished already: True
Letters in banana: 6
7 squared: 49

macOS-style terminal window titled Terminal — ValueTaskFromResult showing dotnet run printing Finished already: True, Letters in banana: 6 and 7 squared: 49

  • IsCompletedSuccessfully was True before anything awaited it: the ValueTask finished when it was made.
  • await letters gave 6, the letters in banana, and await square(7) gave 49.

The Complete File​

macOS-style code window titled Program.cs — ValueTaskFromResult showing a call to CountLettersAsync for banana with its IsCompletedSuccessfully and awaited result, a Func lambda that squares a number with ValueTask.FromResult, and a CountLettersAsync method that returns word.Length with ValueTask.FromResult

Program.cs
// A finished ValueTask<int>, made without async.
ValueTask<int> letters = CountLettersAsync("banana");
Console.WriteLine($"Finished already: {letters.IsCompletedSuccessfully}");
Console.WriteLine($"Letters in banana: {await letters}");

// A lambda that must return a ValueTask<int>.
Func<int, ValueTask<int>> square = number => ValueTask.FromResult(number * number);
Console.WriteLine($"7 squared: {await square(7)}");

// The method must return a ValueTask<int>, but it has the answer at once.
static ValueTask<int> CountLettersAsync(string word)
{
return ValueTask.FromResult(word.Length);
}

Common Mistakes​

MistakeWhat happensDo this instead
Returning the value itself from a method that isn't async, as in return word.Length;error CS0029: Cannot implicitly convert type 'int' to 'System.Threading.Tasks.ValueTask<int>'Return ValueTask.FromResult(word.Length). Or mark the method async: as static async ValueTask<int>, the same return word.Length; built and returned 6
Returning Task.FromResult where a ValueTask is expectederror CS0029: Cannot implicitly convert type 'System.Threading.Tasks.Task<int>' to 'System.Threading.Tasks.ValueTask<int>'Use ValueTask.FromResult
Writing ValueTask.FromResult(null) without a typeerror CS0411: The type arguments for method 'ValueTask.FromResult<TResult>(TResult)' cannot be inferred from the usage. Try specifying the type arguments explicitly.Name the type: with ValueTask.FromResult<string?>(null), it built, and the caller printed No nickname

FAQ​

Is new ValueTask<int>(6) the same?​

It gives a finished ValueTask too: IsCompletedSuccessfully was True, and await gave 6. The reference on that constructor: Initializes a new instance of the ValueTask<TResult> class using the supplied result of a successful operation.

What if the method returns a ValueTask without a result?​

Return ValueTask.CompletedTask. The reference: Gets a task that has already completed successfully. A SaveAsync method that returned it had finished at once, with IsCompletedSuccessfully True, and awaiting it went straight on to the next line.

Conclusion​

ValueTask.FromResult(value) gives you a ValueTask<T> that has already finished with value. Use it in a method or a lambda that must return a ValueTask<T> but has its answer at once, name the type when the value is null, and return ValueTask.CompletedTask when there's no result.

Additional Resources​