Skip to content

ref readonly parameters C# 12.0performancecorrectness

Allow parameters to be passed by reference without being modified.

A ref parameter means the reference (pointer) to the value is provided to the called method rather than the object or value itself.

This was useful if the method needed to modify the reference or if the value was large and there were performance benefits to avoid copying it such as a large struct.

Unfortunately there was no way for a method to indicate that it would not modify the value passed by reference and wanted the reference for performance reasons only.

In C# 12.0 a ref can now be annotated as ref readonly to indicate that passed reference will not be modified and that the reference will not be changed to point to a different value or object.

Code

C#

var bigStruct = new BigStruct();
Process(ref bigStruct);

void Process(ref readonly BigStruct bigStructRef)
{
    // bigStructRef = new BigStruct(); would fail
}
C#

var bigStruct = new BigStruct();
var safeRef = bigStruct; // In case Process changes it
Process(ref safeRef);

void Process(ref BigStruct bigStructRef) 
{
    // ...
}

Notes

  • You can also replace readonly with in on the caller arg to indicate it won't be modified

More information