Lesson 5 of 10

Methods with ref and out

Goal

Copies versus originals, and the TryParse pattern

01

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.

02

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
  1. With 10 and 3, TryDivide returns true and the result 3
  2. Dividing by zero returns false and zero without stopping the program
  3. Heal changes the variable itself, so 50 + 30 = 80
  4. Heal doesn't go over 100
  5. ParseOr reads the number from the text
  6. ParseOr returns the fallback without an exception when the text isn't a number
03

Hints

0/3
Track lessons0 of 10 done

C# is the language behind Unity games and .NET apps. Every variable has a fixed type, programs are built from classes, and it comes with ready-made tools for most of what you need.

Beginner level, 10 lessons, 2.5 hours in total.

Program.cs
OutputC# (Mono 6.6, Judge0)

Compiling and running your code on the server.

–/6

Compiling and running your code on the server.

6 checks listed under “Your task”.

Track lessons0 of 10 done

C# is the language behind Unity games and .NET apps. Every variable has a fixed type, programs are built from classes, and it comes with ready-made tools for most of what you need.

Beginner level, 10 lessons, 2.5 hours in total.