c# · level 1 · unit 7 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
hands the answer back so you can keep it.
So far your functions print things. Printing shows a value on the screen, and then it is gone. Your program cannot catch it, keep it or do maths with it.
To return a value, swap void for a , like int, and end with return and the value. The call then turns into the answer, as if Twice(4) were the number 8.
C# checks that the function really hands something back. Forget the return and it stops with error CS0161 before anything runs.
using System;
int answer = Twice(4);
Console.WriteLine(answer);
Console.WriteLine(Twice(answer));
int Twice(int number)
{
return number * 2;
} Printing is showing someone your answer, and return is handing it to them.
guess first
This one prints instead. What will happen?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
using System;
int answer = Twice(4);
Console.WriteLine(answer);
void Twice(int number)
{
Console.WriteLine(number * 2);
}
your turn
Your turn. Build a dog years machine.
In the first blank, type your dog's age, real or made up. In the second, type how many dog years each year counts as. People often say 7. Then run it.
output
press run to see what happens
fix it
Your score should double, but it stays at 5. Fix it!
output
press run to see what happens
- The function works and hands back 10. But does anything catch that answer?
- Line 4 calls
Twice, but the returned value is dropped on the floor. Store it in a box. - Change line 4 to
score = Twice(score);, then run.
nailed it
your functions can hand back answers. :D
Console.WriteLineshows a value.returnhands it back to use.- The return type says what kind of value comes back.
- Catch a returned value in a box to keep it.
new words in your collection
- return
- return type
This lesson isn’t saved. A free account remembers every lesson you finish.