0
0
CsharpConceptBeginner · 3 min read

What is the in keyword in C# and How to Use It

In C#, the in keyword is used to pass arguments to methods by reference without allowing the method to modify them. It ensures the argument is read-only inside the method, improving performance for large structs by avoiding copying.
⚙️

How It Works

The in keyword in C# tells the compiler to pass a method argument by reference, but only for reading. Imagine you lend a book to a friend but tell them they can only read it and not write notes in it. This way, the book stays the same, but your friend doesn't have to carry a copy.

Normally, when you pass a value type like a struct to a method, C# makes a copy. This can be slow if the struct is large. Using in passes the original data's address, so no copy is made, but the method cannot change the data. This helps keep your program fast and safe.

💻

Example

This example shows a method that takes a large struct using in. The method reads the data but cannot change it.
csharp
using System;

struct Point
{
    public int X, Y;
}

class Program
{
    static void PrintPoint(in Point p)
    {
        Console.WriteLine($"X = {p.X}, Y = {p.Y}");
        // p.X = 10; // This would cause a compile error because p is read-only
    }

    static void Main()
    {
        Point pt = new Point { X = 5, Y = 7 };
        PrintPoint(pt);
    }
}
Output
X = 5, Y = 7
🎯

When to Use

Use the in keyword when you want to pass large value types (like structs) to methods without copying them, but you want to make sure the method does not modify the data. This is useful in performance-critical code where copying large data would slow things down.

For example, in graphics programming or math libraries, structs representing points, vectors, or matrices can be large. Passing them with in saves memory and time while keeping data safe.

Key Points

  • in passes arguments by reference but as read-only.
  • It prevents the method from modifying the argument.
  • Improves performance by avoiding copying large structs.
  • Cannot be used with reference types to enforce read-only.
  • Introduced in C# 7.2 and later.

Key Takeaways

The in keyword passes arguments by reference as read-only to improve performance.
It is ideal for large structs to avoid copying while preventing modification.
Using in helps write safer and faster code in performance-sensitive scenarios.
The method receiving an in parameter cannot change its value.
This feature requires C# 7.2 or newer.