Skip to content

ref and unsafe in iterators and async C# 13.0performancenew scenarios

Allow ref locals and unsafe blocks in iterator and async methods.

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 ​

  • ref locals still cannot be live across a yield return or await expression
  • unsafe blocks are now allowed in iterators, but yield return and yield break must stay in safe code (async methods could already contain unsafe blocks without an await)
  • Enables more natural use of Span<T> and ref in 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 yield or await unsafe.

More information ​

Powered by Intracia