C# 12 features: ref readonly
Part 3 in a series on new language features in C# 12.
ref readonly
modifier
A bit more of a niche feature - if you have code that is passing structs by ref
, but you don't need to (or want to) allow modification of the parameter, you can now indicate it is readonly.
public static void ByRefReadonly(ref readonly Point p)
{
//p = new Point(2, 3);
Console.WriteLine(p);
}
In the code sample above, Point
is a struct or record type. If you uncommented the line then the compiler will emit an error.
Interesting, but I've not come across a need to use this yet.
Further reading
Example source
https://github.com/flcdrg/csharp-12/blob/main/02-collection-expressions/CollectionExpressions.cs
Categories: .NET