C# Method Return Values
So far our methods have used void, meaning they do not send anything back. Often you want a method to calculate something and hand the result back to the code that called it. This is done with a return value, and the void keyword is replaced by the type of the value you return.
Returning a Value
To return a value, declare the return type before the method name and use the return keyword to send a value back. The moment return runs, the method stops and the value is passed to the caller.
A method that returns an int
static int Add(int x, int y)
{
return x + y;
}
static void Main()
{
int result = Add(5, 3);
Console.WriteLine(result); // 8
}Using the Returned Value
Because the method gives back a value, you can store it in a variable, use it in a calculation, or print it directly. This makes methods behave like reusable formulas.
Using a result right away
static int Square(int number)
{
return number * number;
}
static void Main()
{
Console.WriteLine(Square(4)); // 16
int total = Square(3) + Square(2); // 9 + 4
Console.WriteLine(total); // 13
}Return Types Must Match
The value you return must match the declared return type. A method that says it returns a double should hand back a double, and a method that returns a bool should hand back true or false.
Returning a bool
static bool IsEven(int number)
{
return number % 2 == 0;
}
static void Main()
{
Console.WriteLine(IsEven(10)); // True
Console.WriteLine(IsEven(7)); // False
}- Use void when the method just performs an action and returns nothing.
- Use a real type (int, double, string, bool, and so on) when the method produces a result.
- A method can have several return statements, for example one inside an if and one after it.