Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

C# in vs ref vs out: Parameter Passing Explained

Learn how C# in, ref, and out parameter modifiers differ, when to use each, and how they affect method signatures and runtime behavior.

~5 min readC#
#C##parameter modifiers#ref#out
Diagram comparing C# in, ref, and out parameter modifiers with arrows showing data flow.

In C#, the in, ref, and out parameter modifiers change how arguments are passed to methods. By default, passing an argument to a method copies its value: for value types, a copy of the data; for reference types, a copy of the reference. The three modifiers provide the method with access to the caller's variable, with different rules for reading and writing.

The Default Behavior: Passing by Value

Before diving into the modifiers, it helps to recall what happens without them. Consider this method:

csharp
public static void Increment(int number) { number++; } int value = 5; Increment(value); Console.WriteLine(value); // 5

The value variable remains 5 because the method receives a copy of the integer. For a reference type, the reference itself is copied, so the method can modify the object's contents but cannot reassign the caller's variable to a new object. This default behavior is safe and predictable, but it becomes limiting when you need the method to produce a new value or when copying a large struct is expensive.

The out Modifier: Guaranteed Assignment

The out modifier is designed for methods that must produce one or more values. The caller does not need to initialize the variable before passing it, but the method must assign a value to every out parameter before returning. This is a compile-time guarantee.

csharp
public static bool TryParseInt(string input, out int result) { if (int.TryParse(input, out result)) { return true; } result = 0; // Must assign even on failure return false; } if (TryParseInt("42", out int number)) { Console.WriteLine(number); // 42 }

Notice that result is assigned in both branches. The compiler enforces this, so you cannot read an uninitialized out variable. The out modifier is common in the TryParse pattern and in methods that need to return multiple values without creating a tuple or custom type.

The ref Modifier: Read-Write Access

The ref modifier gives the method direct access to the caller's variable. The variable must be initialized before the call, and the method can both read and modify it. Unlike out, the method is not required to assign a new value, but it may do so.

csharp
public static void Swap(ref int a, ref int b) { int temp = a; a = b; b = temp; } int x = 1, y = 2; Swap(ref x, ref y); Console.WriteLine($"{x} {y}"); // 2 1

Here, the method modifies the original variables. ref is useful when you want to avoid copying a large struct or when you need to replace the object a reference type variable points to.

The in Modifier: Read-Only Reference

Introduced in C# 7.2, the in modifier passes a read-only reference to the argument. The method can read the value but cannot modify it. At the call site, in is optional; the compiler lets you omit it. The argument is passed by reference, which avoids copying large structs when the argument is a variable.

csharp
public static void Display(in Vector3 vector) { Console.WriteLine($"({vector.X}, {vector.Y}, {vector.Z})"); } var position = new Vector3(1, 2, 3); Display(in position); // 'in' is optional here Display(position); // also valid

The in modifier is a performance optimization for read-only access to large value types. It is legal for reference types, but rarely useful: passing a reference type by value already passes a reference, and applying in to the reference variable only prevents the method from reassigning the caller's variable. It does not prevent the method from calling mutating members on the referenced object.

Comparing in, ref, and out in Practice

The following table summarizes the key differences:

ModifierCaller must initialize?Method can read?Method can write?Call site syntaxTypical use
inYes (if variable)YesNoin optionalRead-only access to large structs
refYesYesYesref requiredModify the caller's variable
outNoOnly after assignmentYes (must assign)out requiredReturn multiple values

Note that out parameters cannot be read before they are assigned, and the method must assign them before every return path. This makes out a strict contract for output values.

Performance and Large Structs

For value types, passing by value copies the entire struct. If the struct is large, that copy happens on every call. Using in or ref avoids the copy by passing a reference to the original variable. The in modifier is ideal when the method only needs to read the struct, while ref is necessary if the method must modify it.

csharp
public readonly struct Matrix4x4 { public float M11, M12, M13, M14; // Other fields are omitted for brevity. } public static float GetFirstElement(in Matrix4x4 matrix) { return matrix.M11; }

Using in here avoids copying the entire matrix on each call. However, the compiler may still create a defensive copy if the struct is mutable and the method accesses a non-readonly member. To get the full benefit, define the struct as readonly or ensure the method does not trigger a defensive copy.

Common Pitfalls and How to Avoid Them

One frequent mistake is confusing ref and out when calling a method. The call-site syntax must match the declaration exactly. For out, you can use out var to declare the variable inline; for ref, you need an existing variable.

Another pitfall is using ref on a reference type when you only need to modify the object's contents. For example:

csharp
public static void AddItem(List<int> list, int item) { list.Add(item); // No need for ref }

Passing the list by value is sufficient because the reference is copied, but the object is shared. ref would allow reassigning the list variable to a new list, which is rarely needed and can lead to subtle bugs.

When using in, remember that the method cannot assign to the parameter. If you attempt to modify it, the compiler raises an error. Also, for value types that are not readonly, the compiler may create a defensive copy before calling a non-readonly method, negating the performance benefit. Declare the struct as readonly whenever possible.

Choosing the Right Modifier for Your Method

Use out when the method needs to produce one or more output values and the caller should not have to initialize them, such as in the TryParse pattern. Use ref when the method must modify the caller's variable, either to replace it or to swap values. Use in when you have a large value type that should be passed read-only to avoid copying.

A practical decision rule: if the method needs to write to the parameter, use out if the caller does not need to provide an initial value, otherwise use ref. If the method only reads the parameter and the type is a large struct, use in. For small value types or reference types, stick with the default by-value passing to keep the API simple.

When you design a public API, prefer out and ref only when necessary, as they add complexity at the call site. The in modifier is less intrusive because the caller can omit it, but it still signals that the argument is passed by reference, which may affect overload resolution and API readability.

Try matching browser tools

All tools

Small utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.

All C# guides

More in C#

All C# guides

The guides filed next to this one in C#, in library order.