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 with an account.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 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.