ref, out and in
ref: the caller variable
A parameter is a copy. For a struct that means the method works on its own value, and a change inside is invisible to the caller. ref passes the variable itself, so the method writes into the caller slot.
int value = 10;
DoubleIt(ref value);
Console.WriteLine(value);
static void DoubleIt(ref int n) => n *= 2;
dotnet run
20
Both ends carry the keyword: the parameter is declared ref and the call passes ref value. A method may not store a ref parameter in a field, and a call cannot pass a literal, because a literal has no variable to write back into.
out and TryParse
out is the one-way form: the method must assign the parameter before it returns, and the caller gets the value even when the method returns false. That is exactly the shape of a parse that may fail.
if (int.TryParse("42", out int parsed))
{
Console.WriteLine(parsed);
}
Console.WriteLine(int.TryParse("x", out int bad));
Console.WriteLine(bad);
dotnet run
42
False
0
The failed parse wrote 0 into bad, because an
out parameter must be assigned on every path and the
default value is what a failed parse has to offer. A
string? line = Console.ReadLine() parsed with
int.TryParse(line, out var n) is the idiom that
avoids both an exception and a null check.
The declaring call may write out var n and let the
compiler infer the type, which is the form this course uses.
in: a large struct without a copy
A readonly struct passed by value is copied, and a large one costs. in passes a read-only reference: the method sees the caller value, cannot write it, and the copy disappears.
var point = new Point(3, 4);
Console.WriteLine(Length(in point));
static double Length(in Point p) => Math.Sqrt(p.X * p.X + p.Y * p.Y);
readonly struct Point
{
public Point(int x, int y)
{
X = x;
Y = y;
}
public int X { get; }
public int Y { get; }
}
dotnet run
5
Three and four are the legs of a 3-4-5 triangle, so the length is exactly 5.
The call may write in point or leave the keyword out:
the compiler inserts it for an in parameter, which is
why the call site of such a method stays quiet.
in is a performance tool, and a small struct such as
two ints is cheaper to copy than to pass by reference. It pays for a struct
of several fields, and the BCL uses it for spans and for large value types.
The three rules
| Keyword | Who assigns | Reads the old value | Typical use |
|---|---|---|---|
| ref | the caller before the call | yes | change a variable in place |
| out | the method, on every path | no | a second result, as in TryParse |
| in | the caller | yes, read-only | a large struct without a copy |
All three are part of the signature: a method with ref int and one with int are different overloads, and a delegate must describe the keyword too. The keywords are not a way to return several values in general: a tuple, (int sum, int count), is usually the clearer answer, and it costs one object instead of a shared variable.
Exercises
- Remove the ref from the call of DoubleIt and read the error.
- Write bool TryHalf(int value, out int half) that fails on an odd number, and call it with both kinds of input.
- Change Length to take the struct by value and count the copies with a field that the constructor increments. How many copies does each form make?
- Return the sum and the count of an array from one method with a tuple instead of two out parameters.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does ref do to a parameter?
Answer
It passes the caller variable, so the method can change it
A ref parameter is an alias for the variable at the call, so a write inside the method is visible after it.
-
Which keyword promises that the method assigns the parameter itself?
Answer
out
An out parameter carries no value in, and the compiler requires the method to assign it on every path.
-
What does this program print?
int value = 10; Double(ref value); Console.WriteLine(value); static void Double(ref int n) => n *= 2;Answer
20
The method writes into the caller variable, so the value is doubled when it returns.
-
What does int.TryParse write into its out parameter when the text is not a number?
Answer
0, the default value of int
An out parameter must be assigned on every path, and a failed parse assigns the default value of the type.
-
What does this program print?
Console.WriteLine(int.TryParse("42", out int n)); Console.WriteLine(n);Answer
True / 42
The parse succeeds, returns true and writes 42 into n, which the out declaration brought into scope.
-
What is an in parameter for?
Answer
Passing a large struct by reference without allowing a write
in passes a read-only reference, which saves the copy of a big value type and keeps the method from changing it.
-
What does this program print?
int a = 3; Change(ref a); Console.WriteLine(a); static void Change(ref int x) => x = 7;Answer
7
The method writes 7 into the caller variable, so the value after the call is 7.
-
Which call is not allowed for a ref parameter?
Answer
Passing a literal such as 5
A literal is not a variable, so there is nothing for the method to write into.
-
What does this program print?
var point = new Point(3, 4); Console.WriteLine(Length(in point)); static double Length(in Point p) => Math.Sqrt(p.X * p.X + p.Y * p.Y); readonly struct Point { public Point(int x, int y) { X = x; Y = y; } public int X { get; } public int Y { get; } }Answer
5
The square root of 9 plus 16 is exactly 5, and the in parameter reads the struct without a copy.
-
Why is a tuple often better than two out parameters?
Answer
It returns one value with named parts and needs no variable declared by the caller
A tuple keeps the result in the return position, which reads better and works with async and LINQ, where out does not.
The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev