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.
in
?Performance: Avoids copying large structs when passing them to methods.
Safety: Ensures the struct cannot be modified within the method.
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}");
Performance Gain:
When passing large structs (e.g., Point
with many fields), in
avoids the overhead of copying the struct.
Immutability:
The in
modifier ensures the struct cannot be modified within the method, making the code safer.
Use Cases:
Passing large structs to methods (e.g., 3D graphics, mathematical calculations).
Performance-critical code where avoiding copies is important.
Don’t use in
for small structs or reference types (e.g., classes). The overhead of dereferencing may outweigh the benefits.