TExcelTAD
Home › C# › C# Return Values

C# Return Values

A method can send a result back to its caller with the return keyword. The type of that result is written before the method name instead of void.

Returning a value

csharp · try it yourself
using System;

class Program
{
    static int Multiply(int a, int b)
    {
        return a * b;
    }

    static string Describe(int n)
    {
        return n % 2 == 0 ? "even" : "odd";
    }

    static void Main()
    {
        int area = Multiply(6, 7);
        Console.WriteLine(area);
        Console.WriteLine(Multiply(area, 2));
        Console.WriteLine(
quot;9 is {Describe(9)}"); } }
42
84
9 is odd

The returned value can be stored in a variable, passed straight to another method, or used inside an expression — anywhere a value of that type is allowed.

return ends the method

return immediately leaves the method. Code after it in the same path does not run. This makes early returns a clean way to handle special cases first:

csharp · try it yourself
using System;

class Program
{
    static string Classify(int age)
    {
        if (age < 0) return "invalid";
        if (age < 13) return "child";
        if (age < 20) return "teen";
        return "adult";
    }

    static void Main()
    {
        int[] ages = { -1, 7, 16, 45 };
        foreach (int a in ages)
            Console.WriteLine(
quot;{a}: {Classify(a)}"); } }
-1: invalid
7: child
16: teen
45: adult

A non-void method must return a value on every possible path. If one path can reach the end without return, the compiler reports error CS0161 ("not all code paths return a value"):

csharp
static string Sign(int n)
{
    if (n > 0) return "positive";
    if (n < 0) return "negative";
    // error CS0161: what about n == 0?
}

In a void method you can use a bare return; to exit early.

Returning multiple values with tuples

A method has only one return type, but that type can be a tuple that groups several values. Name the elements for readable code, and deconstruct the result into separate variables at the call site.

csharp · try it yourself
using System;

class Program
{
    static (int Min, int Max, double Average) Stats(int[] values)
    {
        int min = values[0], max = values[0], sum = 0;
        foreach (int v in values)
        {
            if (v < min) min = v;
            if (v > max) max = v;
            sum += v;
        }
        return (min, max, (double)sum / values.Length);
    }

    static void Main()
    {
        int[] data = { 4, 8, 15, 16, 23, 42 };

        var result = Stats(data);
        Console.WriteLine(
quot;Min {result.Min}, Max {result.Max}"); var (lo, hi, avg) = Stats(data); Console.WriteLine(
quot;{lo}..{hi}, average {avg:F2}"); } }
Min 4, Max 42
4..42, average 18.00

Returning arrays and objects

Any type can be returned, including arrays and objects:

csharp · try it yourself
using System;

class Program
{
    static int[] FirstMultiples(int n, int count)
    {
        int[] result = new int[count];
        for (int i = 0; i < count; i++)
            result[i] = n * (i + 1);
        return result;
    }

    static void Main()
    {
        Console.WriteLine(string.Join(", ", FirstMultiples(7, 5)));
    }
}
7, 14, 21, 28, 35

Summary

Return type What return needs Example
void Nothing (return; is optional) static void Print()
int, string, … A value of that type on every path return a + b;
Tuple (int, string) A tuple literal return (1, "one");
Array / object A reference of that type return new int[3];

Tip: Prefer methods that return results over methods that print them. A returned value can be printed, tested, stored or combined; printed text can only be read.

Test yourself

What happens to code placed directly after a return statement in the same block?

  1. It runs after the caller finishes
  2. It never runs
  3. It runs before returning
  4. It causes a runtime error

Which declaration returns two values?

  1. static int, int Pair()
  2. static (int, int) Pair()
  3. static int[2] Pair()
  4. static void Pair() returns (int, int)

What does compiler error CS0161 'not all code paths return a value' mean?

  1. The method is never called
  2. Some path through a non-void method can end without returning
  3. The method returns the wrong type
  4. A void method uses return