---
title: "C# 13: Allow ref and unsafe in iterators and async"
description: "C# 13 might get a new feature soon that allows `ref` and `unsafe` in iterators and async methods. "
updated: 2024-03-25
tags: ["C#", "C# 13", ".NET", ".NET 9"]
canonical: "https://steven-giesel.com/blogPost/0d4216e5-4445-48c4-8d9c-3ff5aa1bfdc3/c-13-allow-ref-and-unsafe-in-iterators-and-async"
---

# C# 13: Allow ref and unsafe in iterators and async

C# 13 might get a new feature soon that allows `ref` and `unsafe` in iterators and async methods. 

## Motivation
In the current world you can not do this:
```csharp
async Task MyMethodAsync()
{
    await AnAsyncMethod();
    ref int x = ref GetRef();
    DoSomething(ref x);
    await AnohterAsnycMethod();
}
```

The problem with `await` and `ref` is that the compiler can not guarantee that the reference is still valid after the `await`. 
But in the given case above, that shouldn't be an issue, as `x` is only used between two `await` calls, where the reference is still valid.

The same applies to `ref struct`s like `Span<T>` or `ReadOnlySpan<T>`. You can't use them in iterators (`yield`) or async methods.

The proposal would exactly allow that:

```csharp
async Task MyMethodAsync()
{
    var result = await AnAsyncMethod();
    ReadOnlySpan<char> span = result.AsSpan();
    DoSomething(span);
    await AnohterAsnycMethod();
}
```

The read more about the proposal, see the [original proposal](https://github.com/jjonescz/csharplang/blob/state-machine-restrictions/proposals/ref-unsafe-in-iterators-async.md).