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
csharp
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));
}csharp
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
- Callers can omit
inat the call site, and can pass values such as literals, which the compiler stores in a temporary - Calling members on a non-readonly struct through an
inparameter makes defensive copies; use a readonly struct C# 7.2 to avoid them - ref readonly parameters C# 12.0 complement
infor APIs that require a variable to be passed by reference