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

3/25/2024
1 minute read

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

struct vs readonly struct vs ref struct vs record struct

C# knows struct since its down of time. But there are also recent additions like readonly struct, record struct and ref struct.

This article will show what are the differences between those 4.

The first possible new feature of C# 13: Params collection

Only one month after the big release of .NET 8, the dotnet team is already working on the next iteration: .NET 9. With that also comes new language features. The first one is about to be merged into the main development branch: Params Collections.

The state machine in C# with async/await

You often here that the async/await keywords leads to a state machine. But what does that mean? Let's discuss this with a simple example.

An error has occurred. This application may no longer respond until reloaded. Reload x