Iterator methods (using yield) and async methods (using await) previously banned all ref locals and locals of ref struct types such as Span<T>, even in sections that did not cross a yield or await boundary. Iterators also could not contain unsafe code at all. This forced developers to refactor code into separate helper methods.
C# 13 relaxes these restrictions. ref locals and ref struct locals are now allowed as long as they are not used across a yield return or await, and iterators can contain unsafe blocks.
Code
csharp
using System.Runtime.CompilerServices;
IEnumerable<int> DoubleValues(int[] values)
{
foreach (var value in values)
{
ref var item = ref Unsafe.AsRef(in value);
yield return item * 2;
}
}
async Task ProcessAsync(int[] data)
{
Span<int> buffer = stackalloc int[10];
Fill(buffer);
await SendAsync(buffer.ToArray());
}csharp
IEnumerable<int> DoubleValues(int[] values)
{
// ref locals were not allowed at all in iterator methods
// even though they don't cross a yield boundary
foreach (var value in values)
{
var item = value;
yield return item * 2;
}
}
async Task ProcessAsync(int[] data)
{
// Span and stackalloc were not allowed in async methods
var buffer = new int[10];
Fill(buffer);
await SendAsync(buffer);
}Notes
reflocals still cannot be live across ayield returnorawaitexpressionunsafeblocks are now allowed in iterators, butyield returnandyield breakmust stay in safe code (async methods could already containunsafeblocks without anawait)- Enables more natural use of
Span<T>andrefin async and iterator methods - See ref fields and scoped ref C# 11.0 for holding refs in a struct, which is the synchronous form of what this feature allows in iterators.
- See the async programming guide for the lifetime rules that make refs across a
yieldorawaitunsafe.