12 minlesson

Return Values

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:

csharp
1static int Add(int a, int b)
2{
3 return a + b;
4}
5
6int result = Add(3, 5);
7Console.WriteLine(result); // 8

Return Type

The return type is declared before the method name:

csharp
1// Returns an integer
2static int GetAge()
3{
4 return 25;
5}
6
7// Returns a string
8static string GetName()
9{
10 return "Alice";
11}
12
13// Returns a boolean
14static bool IsValid()
15{
16 return true;
17}
18
19// Returns a double
20static 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
csharp
1// void - no return value
2static void PrintMessage()
3{
4 Console.WriteLine("Hello");
5 // No return needed (or use 'return;' to exit early)
6}
7
8// int - returns a value
9static int Square(int n)
10{
11 return n * n; // Must return an int
12}

Using Return Values

Return values can be:

Stored in Variables

csharp
1int doubled = Double(5);
2Console.WriteLine(doubled); // 10
3
4static int Double(int n) => n * 2;

Used Directly in Expressions

csharp
1Console.WriteLine(Add(3, 4)); // 7
2Console.WriteLine($"Sum: {Add(10, 20)}"); // Sum: 30
3
4int total = Add(1, 2) + Add(3, 4); // 3 + 7 = 10

Passed to Other Methods

csharp
1int squared = Square(Double(3)); // Double(3)=6, Square(6)=36
2
3static int Double(int n) => n * 2;
4static int Square(int n) => n * n;

Used in Conditions

csharp
1if (IsEven(10))
2{
3 Console.WriteLine("10 is even");
4}
5
6static bool IsEven(int n) => n % 2 == 0;

Early Return

return immediately exits the method:

csharp
1static int Divide(int a, int b)
2{
3 if (b == 0)
4 {
5 Console.WriteLine("Cannot divide by zero!");
6 return 0; // Exit early
7 }
8 return a / b; // Normal return
9}
10
11static string GetGrade(int score)
12{
13 if (score < 0 || score > 100)
14 {
15 return "Invalid"; // Exit early for invalid input
16 }
17
18 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

csharp
1static 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}
10
11int[] numbers = CreateRange(5, 3); // [5, 6, 7]

Returning Tuples

Return multiple values without out parameters:

csharp
1static (int min, int max) GetMinMax(int[] numbers)
2{
3 int min = numbers[0];
4 int max = numbers[0];
5
6 foreach (int n in numbers)
7 {
8 if (n < min) min = n;
9 if (n > max) max = n;
10 }
11
12 return (min, max);
13}
14
15int[] data = { 5, 2, 8, 1, 9 };
16var result = GetMinMax(data);
17Console.WriteLine($"Min: {result.min}, Max: {result.max}");
18
19// Or deconstruct
20var (minimum, maximum) = GetMinMax(data);
21Console.WriteLine($"Min: {minimum}, Max: {maximum}");

Named Tuple Elements

csharp
1static (string name, int age, string city) GetPerson()
2{
3 return ("Alice", 30, "New York");
4}
5
6var person = GetPerson();
7Console.WriteLine($"{person.name} is {person.age} from {person.city}");

Practical Examples

Calculate Average

csharp
1static double CalculateAverage(int[] numbers)
2{
3 if (numbers.Length == 0)
4 return 0;
5
6 int sum = 0;
7 foreach (int n in numbers)
8 {
9 sum += n;
10 }
11 return (double)sum / numbers.Length;
12}
13
14int[] scores = { 85, 90, 78, 92, 88 };
15double avg = CalculateAverage(scores);
16Console.WriteLine($"Average: {avg:F2}"); // Average: 86.60

Password Validator

csharp
1static bool IsValidPassword(string password)
2{
3 if (password.Length < 8)
4 return false;
5
6 bool hasUpper = false;
7 bool hasLower = false;
8 bool hasDigit = false;
9
10 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 }
16
17 return hasUpper && hasLower && hasDigit;
18}
19
20Console.WriteLine(IsValidPassword("weak")); // False
21Console.WriteLine(IsValidPassword("StrongPass1")); // True

Temperature Converter

csharp
1static double CelsiusToFahrenheit(double celsius)
2{
3 return celsius * 9 / 5 + 32;
4}
5
6static double FahrenheitToCelsius(double fahrenheit)
7{
8 return (fahrenheit - 32) * 5 / 9;
9}
10
11Console.WriteLine($"0°C = {CelsiusToFahrenheit(0)}°F"); // 32
12Console.WriteLine($"100°C = {CelsiusToFahrenheit(100)}°F"); // 212
13Console.WriteLine($"98.6°F = {FahrenheitToCelsius(98.6):F1}°C"); // 37.0

Chaining Methods

csharp
1static string FormatName(string name)
2{
3 return name.Trim().ToUpper();
4}
5
6static string Greet(string name)
7{
8 return $"Hello, {FormatName(name)}!";
9}
10
11static string CreateMessage(string name, int visits)
12{
13 string greeting = Greet(name);
14 return $"{greeting} This is visit #{visits}.";
15}
16
17string message = CreateMessage(" alice ", 5);
18Console.WriteLine(message); // Hello, ALICE! This is visit #5.

Summary

In this lesson, you learned:

  • Methods return values using the return statement
  • Return type is declared before the method name
  • void means 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.

Return Values - Anko Academy