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:
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:
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.