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

25/03/2024

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.

ASP.NET Core - Why async await is useful

Did you ever wonder why you "should" use async and await in your ASP.NET Core applications? Most probably, you heard something about performance. And there is some truth to it, but not in the way you might think.

So let's discuss this with smaller examples.

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