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.

Time O(1)Space O(1)Code C#
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 5

Tips

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.