Lesson 5 of 10
Methods with ref and out
- 13 min
- 6 checks
- 3 hints
- Go to task
Goal
Copies versus originals, and the TryParse pattern
Explanation
When you pass a variable to a method, the method gets a copy of its value, so static void Reset(int hp) { hp = 0; } zeroes only its own copy, and the caller's original variable stays as it was. And with return, a method can hand back only one value.
ref passes the variable itself instead of a copy, so any change the method makes shows up in the original variable. You write ref both in the method's definition and in the call, as in static void Heal(ref int hp, int amount) and then Heal(ref playerHp, 30);, and the variable must already hold a value before you pass it.
Use out when you want a method to hand back an extra value. The method must put a value in an out variable before it finishes, and you can declare that variable right inside the call. This is the idea behind the Try pattern: int.TryParse("42", out int n) returns true and puts 42 in n, and if you give it "abc", it returns false and puts zero there without throwing an exception. int.Parse("abc"), on the other hand, throws a FormatException and stops the program.
Your task
Complete TryDivide(a, b, out result) using the Try pattern: if b is zero, return false and set result to zero, and otherwise return true and set it to a / b. Then complete Heal(ref hp, amount) to increase hp itself by amount without going over 100, and ParseOr(text, fallback) to return the number written in the text using int.TryParse, or fallback if the text isn't a number.
Checks
6 checks- With 10 and 3, TryDivide returns true and the result 3
- Dividing by zero returns false and zero without stopping the program
- Heal changes the variable itself, so 50 + 30 = 80
- Heal doesn't go over 100
- ParseOr reads the number from the text
- ParseOr returns the fallback without an exception when the text isn't a number