Sunday, August 04, 2024

C# Using ref and unsafe in async methods and iterators C# 13

 Using ref and unsafe in async methods and iterators

Before C# 13, declaring local ref variables or local variables of a ref struct type in either async methods or methods that use yield return, commonly known as iterator methods, was not possible. Nor could these methods have an unsafe context. C# 13 allows the declaration of ref local variables and local variables of a ref struct type in asynchronous methods. Similarly, C# 13 allows unsafe contexts in iterator methods.

You can also safely use types like System.ReadOnlySpan<T> in asynchronous and iterator methods. 

The primary benefit of using a ref struct is to get the benefit of pointers in a safe context and prevent memory allocation in several common scenarios. Hence, by using ref struct types in async methods and iterators, you can improve the performance of your application. This is the most useful new feature in C# 13 in my opinion.

C# 13 allows you to make a type argument a ref struct by specifying allows ref struct in the where clause of the type parameter. Note that if you use a type parameter specified with allows ref struct, then you are including all of the behaviors and restrictions of the ref struct type.

Consider the following piece of code that shows a ref struct and a method that uses it as a parameter.

ref struct TestStruct
{

}

TestStruct TestMethod<TestStruct>(TestStruct p)
    where TestStruct : allows ref struct
    => p;

The following code snippet illustrates how ref struct instances can be created and used inside an async method.

async Task<int> Test()
{
    TestStruct testStruct = new TestStruct();
    TestMethod(testStruct);
    return await Task.FromResult(0);
}

No comments:

Be A Developer That Uses AI

Developers will not be replaced by AI, they'll be replaced by developers that use AI. Generative AI tools are revolutionizing the way de...