C# › Fundamentals

How do 'ref', 'out', and 'in' parameter modifiers differ in how they pass arguments to a method?

Intermediate

Answer

'ref' passes a variable BY REFERENCE, requiring it to be initialized before the call, and lets the method both read AND modify it; 'out' also passes by reference but doesn't require prior initialization, and the method MUST assign it before returning; 'in' passes by reference but READ-ONLY, preventing the method from modifying it (used mainly for performance with large structs, avoiding a copy).
void Increment(ref int x) { x++; } // must be initialized before calling
void TryParse(out int result) { result = 42; } // no need to initialize first, must be set inside
void ReadOnly(in int x) { /* x++; // Error: can't modify an 'in' parameter */ }
Real-world example Using 'out' for a TryParse-style method returning both a success bool and a result value; 'ref' for an in-place increment/swap operation.

Common follow-ups: Why would you use 'in' specifically for a large struct parameter rather than passing it normally by value?