Return values
Learn to return a value from a method with return.
Return values
A method can return a value. The return type is a type name instead of void, and the body uses return to give the value. Example: static int Add(int a, int b) { return a + b; }.
When return runs, the method ends and the value goes back to the caller. If the return type is not void, every code path must end with a return.
return and flow
As soon as return runs, the method ends; the code after it does not run. This behavior can be used for an early return: when a condition is met, you end the method immediately.
In void methods you can also exit early with return;; in this case no value is given, only the flow ends. This simplifies code in conditional branches.
Exercise Add method
Define a static int Add(int a, int b) method; in the body write return a + b;. In Main, call it with int sum = Add(5, 7); and print sum with Console.WriteLine.
Show example solution
Write return a + b; in the Add body, add int sum = Add(5, 7); Console.WriteLine(sum); in Main.
Example solution:
using System;
class Program
{
static int Add(int a, int b)
{
// Return the sum
return a + b;
}
static void Main()
{
// Call Add and print the result
int sum = Add(5, 7);
Console.WriteLine(sum);
}
}
Test yourself
-
Match each expression to its meaning
- return 5;
- Returns 5
- static int
- Returns int
- return;
- Exits flow
- int sum = Add(2,3)
- Stores result
-
What does the Add(3, 4) call print?
static int Add(int a, int b) { return a + b; } int sum = Add(3, 4); Console.WriteLine(sum);- 3
- 4
- 7
- 12
Show answer
7 — Correct. Add(3, 4) returns 7; Console prints 7.
-
return statement
static int Square(int n) { ____ }Show answer
static int Square(int n) { return n * n; }