Return Values
Methods can compute and return values to the calling code. This makes them even more powerful and flexible.
The return Statement
Use return to send a value back from a method:
csharp1static int Add(int a, int b)2{3 return a + b;4}56int result = Add(3, 5);7Console.WriteLine(result); // 8
Return Type
The return type is declared before the method name:
csharp1// Returns an integer2static int GetAge()3{4 return 25;5}67// Returns a string8static string GetName()9{10 return "Alice";11}1213// Returns a boolean14static bool IsValid()15{16 return true;17}1819// Returns a double20static double CalculateTax(double amount)21{22 return amount * 0.08;23}
void vs Return Type
void: Method doesn't return anything- Other types (
int,string, etc.): Method returns a value
csharp1// void - no return value2static void PrintMessage()3{4 Console.WriteLine("Hello");5 // No return needed (or use 'return;' to exit early)6}78// int - returns a value9static int Square(int n)10{11 return n * n; // Must return an int12}
Using Return Values
Return values can be:
Stored in Variables
csharp1int doubled = Double(5);2Console.WriteLine(doubled); // 1034static int Double(int n) => n * 2;
Used Directly in Expressions
csharp1Console.WriteLine(Add(3, 4)); // 72Console.WriteLine($"Sum: {Add(10, 20)}"); // Sum: 3034int total = Add(1, 2) + Add(3, 4); // 3 + 7 = 10
Passed to Other Methods
csharp1int squared = Square(Double(3)); // Double(3)=6, Square(6)=3623static int Double(int n) => n * 2;4static int Square(int n) => n * n;
Used in Conditions
csharp1if (IsEven(10))2{3 Console.WriteLine("10 is even");4}56static bool IsEven(int n) => n % 2 == 0;
Early Return
return immediately exits the method:
csharp1static int Divide(int a, int b)2{3 if (b == 0)4 {5 Console.WriteLine("Cannot divide by zero!");6 return 0; // Exit early7 }8 return a / b; // Normal return9}1011static string GetGrade(int score)12{13 if (score < 0 || score > 100)14 {15 return "Invalid"; // Exit early for invalid input16 }1718 if (score >= 90) return "A";19 if (score >= 80) return "B";20 if (score >= 70) return "C";21 if (score >= 60) return "D";22 return "F";23}
Returning Complex Types
Returning Arrays
csharp1static int[] CreateRange(int start, int count)2{3 int[] result = new int[count];4 for (int i = 0; i < count; i++)5 {6 result[i] = start + i;7 }8 return result;9}1011int[] numbers = CreateRange(5, 3); // [5, 6, 7]
Returning Tuples
Return multiple values without out parameters:
csharp1static (int min, int max) GetMinMax(int[] numbers)2{3 int min = numbers[0];4 int max = numbers[0];56 foreach (int n in numbers)7 {8 if (n < min) min = n;9 if (n > max) max = n;10 }1112 return (min, max);13}1415int[] data = { 5, 2, 8, 1, 9 };16var result = GetMinMax(data);17Console.WriteLine($"Min: {result.min}, Max: {result.max}");1819// Or deconstruct20var (minimum, maximum) = GetMinMax(data);21Console.WriteLine($"Min: {minimum}, Max: {maximum}");
Named Tuple Elements
csharp1static (string name, int age, string city) GetPerson()2{3 return ("Alice", 30, "New York");4}56var person = GetPerson();7Console.WriteLine($"{person.name} is {person.age} from {person.city}");
Practical Examples
Calculate Average
csharp1static double CalculateAverage(int[] numbers)2{3 if (numbers.Length == 0)4 return 0;56 int sum = 0;7 foreach (int n in numbers)8 {9 sum += n;10 }11 return (double)sum / numbers.Length;12}1314int[] scores = { 85, 90, 78, 92, 88 };15double avg = CalculateAverage(scores);16Console.WriteLine($"Average: {avg:F2}"); // Average: 86.60
Password Validator
csharp1static bool IsValidPassword(string password)2{3 if (password.Length < 8)4 return false;56 bool hasUpper = false;7 bool hasLower = false;8 bool hasDigit = false;910 foreach (char c in password)11 {12 if (char.IsUpper(c)) hasUpper = true;13 if (char.IsLower(c)) hasLower = true;14 if (char.IsDigit(c)) hasDigit = true;15 }1617 return hasUpper && hasLower && hasDigit;18}1920Console.WriteLine(IsValidPassword("weak")); // False21Console.WriteLine(IsValidPassword("StrongPass1")); // True
Temperature Converter
csharp1static double CelsiusToFahrenheit(double celsius)2{3 return celsius * 9 / 5 + 32;4}56static double FahrenheitToCelsius(double fahrenheit)7{8 return (fahrenheit - 32) * 5 / 9;9}1011Console.WriteLine($"0°C = {CelsiusToFahrenheit(0)}°F"); // 3212Console.WriteLine($"100°C = {CelsiusToFahrenheit(100)}°F"); // 21213Console.WriteLine($"98.6°F = {FahrenheitToCelsius(98.6):F1}°C"); // 37.0
Chaining Methods
csharp1static string FormatName(string name)2{3 return name.Trim().ToUpper();4}56static string Greet(string name)7{8 return $"Hello, {FormatName(name)}!";9}1011static string CreateMessage(string name, int visits)12{13 string greeting = Greet(name);14 return $"{greeting} This is visit #{visits}.";15}1617string message = CreateMessage(" alice ", 5);18Console.WriteLine(message); // Hello, ALICE! This is visit #5.
Summary
In this lesson, you learned:
- Methods return values using the
returnstatement - Return type is declared before the method name
voidmeans no return value; other types require a return- Return values can be used in expressions, stored, or passed to other methods
- Early returns can simplify code with conditions
- Tuples allow returning multiple values
Next, we'll learn about method overloading.