0008 The in Modifier for Performance Optimisation

The in modifier in C# is used to pass arguments by reference in a way that ensures they cannot be modified. It’s particularly useful for improving performance when working with large structs.

Why use in?

Example:

public struct Point
{
    public int X;
    public int Y;
}

public double CalculateDistance(in Point p1, in Point p2)
{
    // p1 and p2 are passed by reference but cannot be modified
    int dx = p1.X - p2.X;
    int dy = p1.Y - p2.Y;
    return Math.Sqrt(dx * dx + dy * dy);
}

// Usage
Point point1 = new Point { X = 1, Y = 2 };
Point point2 = new Point { X = 4, Y = 6 };
double distance = CalculateDistance(in point1, in point2);
Console.WriteLine($"Distance: {distance}");

Key Points:

  1. Performance Gain:

  2. Immutability:

  3. Use Cases:

Gotcha: