String.Create with Spans
04/20/2025
One new C# feature with .NET 9 is the ability to define allows ref struct
as a generic type constraint. It sounds contradictory to refer to this as a constraint, because it allows more types to be used with the given method. However, it can also limit how those generic type parameters maybe used in methods. Allowing ref structs allows ref struct types to be used as generic type parameters. The most common ref struct types are the built-in Span<T>
and ReadOnlySpan<T>
but this constraint allows for any custom ref structs as well. In C# ref struct types are special as they must live on the stack, and must not escape to the managed heap.
The C# compiler makes sure that ref struct types are used correctly, and in this sense, it poses as a constraint. For example, in the code snippet below MyType
compiles without the constraint:
public class MyType<T> // where T : allows ref struct { private T _field; public T MyCreate(Func<T> myfunc) { var value = myfunc(); _field = value; return value; } }
However, if we uncomment the where T : allows ref struct
constraint, the compiler issues the following error for _field
: Field or auto-implemented property cannot be of type 'T' unless it is an instance member of a ref struct.