Learn C# · lesson 24 of 61 · about 9 minutes
ref, out and Scope
Rest at the fountain: see that arguments are copies, change the hero's HP with ref, return extra results with out, and see where variables live.
What you'll learn
- Know that ints are passed as copies
- Change a caller's variable with ref
- Explain local scope
The fountain
After the fight, the hero rests at a fountain that heals 25 HP, but never above 100. A method Rest(int hp) would only change its own copy, so heroHp would stay the same. With ref, the method gets heroHp itself: Rest(ref heroHp);.
Copies, ref and out
Normally a method gets a copy of an int, double or bool: changing it inside doesn't affect the caller.
refpasses the variable itself, so changes stick:AddBonus(ref score);outis for extra results the method must set: you've already used it inint.TryParse(text, out int n)
Scope: a variable exists only inside the braces where it's declared. Each method has its own local variables.
A copy can't change the original
int lives = 3;
TryToChange(lives);
Console.WriteLine(lives);
static void TryToChange(int n) { n = 0; }Output
3Copy, ref and out
int score = 10;
TryToChange(score);
Console.WriteLine(score);
AddBonus(ref score);
Console.WriteLine(score);
Divide(17, 5, out int quotient, out int remainder);
Console.WriteLine($"17 / 5 = {quotient} r {remainder}");
static void TryToChange(int n) { n = 99; Console.WriteLine($"inside: {n}"); }
static void AddBonus(ref int n) { n += 5; }
static void Divide(int a, int b, out int q, out int r) { q = a / b; r = a % b; }Output
inside: 99
10
15
17 / 5 = 3 r 2Tip
static keeps a method to its own parameters and variables: if it reaches for a variable of the main code, C# refuses. That's why these methods are all static: everything they need comes in through their parameters.
Now try it yourself
This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.