Differences between ref, out and in in C#
Three keywords for passing parameters in C#: when ref changes, when out returns and when in only reads – with examples and a comparison table.
ref – I’m here to change things
Imagine sending someone out with a shopping list, but with the option to write notes back on the list and return it to you. That is exactly the essence of ref: you pass a variable to a function, and the function can both read and change the original value.
void UpdateValue(ref int number) {
number += 10;
}
int myNumber = 5;
UpdateValue(ref myNumber);
Console.WriteLine(myNumber); // Output: 15out – wait, I’ll get back to you with an answer
You know the situation where you return more than one value from a function? Instead of doing a return with a Tuple or a clumsy object, out gives you a quick way to return values through parameters.
void GetValues(out int a, out int b) {
a = 10;
b = 20;
}
int x;
int y;
GetValues(out x, out y);
Console.WriteLine(
$"x: {x}, y: {y}"
); // Output: x: 10, y: 20in – just look, don’t touch
Meet in, the younger, calm sibling of the family. Unlike the older siblings (who have to change values or return answers), it only wants to read the values. This saves time and energy, especially when large objects are involved.
void PrintValue(in int number) {
Console.WriteLine(number);
// number = 10; // Error: cannot change the value of an in parameter
}
int myNumber = 5;
PrintValue(myNumber);Comparison table
| Feature | ref | out | in |
|---|---|---|---|
| Read inside the function | Yes | Yes | Yes |
| Write inside the function | Yes | Yes | No |
| Must be initialized before the call | Yes | No | Yes |
Why does it matter?
Because code optimizations are not a dirty word. Using these keywords doesn’t just bring order; it also helps us keep the code efficient, simple and clearly understood.