Skip to content

In parameter modifiers C# 7.2correctnessperformance

Pass parameters by reference without allowing modifications.

C# 7.2 brings in to parameter modifiers telling the compiler to error if an attempt is made to modify the value within the method.

This is particularly useful for large structs where passing by value would be expensive, but you want to guarantee the method cannot modify the original.

Code

C#
public double CalculateDistance(in Point a, in Point b)
{
    // a and b are passed by reference but cannot be modified
    return Math.Sqrt(Math.Pow(b.X - a.X, 2) + Math.Pow(b.Y - a.Y, 2));
}
C#
public double CalculateDistance(Point a, Point b)
{
    // a and b are full copies of the structs
    return Math.Sqrt(Math.Pow(b.X - a.X, 2) + Math.Pow(b.Y - a.Y, 2));
}

Notes

WARNING

in parameters are superseded by the ref readonly C# 12.0 which guarantees no copying of the value.

More information