Passing by value, ref and out
By default a method gets a copy of the argument. ref and out hand over the caller's variable itself.
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.The idea
Without a keyword, the parameter is a new variable holding a copy. With ref or out, the parameter is another name for the caller's variable, so assignments inside the method land in the caller.
Code
static void ByValue(int x) { x = 99; }
static void ByRef(ref int x) { x = 99; }
static void Init(out int x) { x = 5; }
int a = 1;
ByValue(a); // a is still 1
ByRef(ref a); // a is now 99
Init(out int b); // b is 5public class Main {
static void byValue(int x) { x = 99; }
static void byRef(int[] x) { x[0] = 99; } // Java has no ref: mutate a shared array
static int init() { return 5; } // Java has no out: return the value
public static void main(String[] args) {
int a = 1;
byValue(a); // a is still 1
int[] box = {a}; byRef(box); a = box[0]; // a is now 99
int b = init(); // b is 5
}
}void byValue(int x) { x = 99; }
void byRef(int& x) { x = 99; }
void init(int& x) { x = 5; } // C++ has no out: a reference parameter plays that role
int main() {
int a = 1;
byValue(a); // a is still 1
byRef(a); // a is now 99
int b; init(b); // b is 5
}def by_value(x: int) -> None: x = 99
def by_ref(box: list[int]) -> None: box[0] = 99 # no ref: mutate a shared container
def init() -> int: return 5 # no out: return the value
a = 1
by_value(a) # a is still 1
box = [a]; by_ref(box); a = box[0] # a is now 99
b = init() # b is 5Tips
- ref: the variable must be initialised before the call. out: it need not be, but the method must assign it before returning.
- Passing a class instance by value still copies only the reference, so the method can change the object but cannot make the caller point at a different one.
In the .NET library
int.TryParse(text, out int n) and dictionary.TryGetValue(key, out var v) are the out pattern you will use every day.