C# 7.2 added two new features:
In Parameters
Using
infor a parameter let's us pass by reference, but then prevents us from assigning a value to it. However the performance can actually become worse, because it creates a "defensive copy" of the struct, copying the whole thingReadonly Structs
A way around this is to use
readonlyfor astruct. When you pass it into aninparameter, the compiler sees that it'sreadonlyand won't create the defensive copy, thereby making it the better alternative for preformance.
That's all great, but every field in the struct has to be readonly. This doesn't work:
public readonly struct Coord
{
public int X, Y; // Error: instance fields of readonly structs must be read only
}
Auto-properties also have to be readonly.
Is there a way to get the benefits of in parameters (compile-time checking to enforce that the parameter isn't changed, passing by reference) while still being able to modify the fields of the struct, without the significant performance hit of in caused by creating the defensive copy?