Multiple Return Values in C#

C# supports multiple return values through the use of tuples. This feature is often used to return both result and error values from a function.

using System;

class Program
{
    // This method returns a tuple (int, int)
    static (int, int) Vals()
    {
        return (3, 7);
    }

    static void Main()
    {
        // Here we use tuple deconstruction to assign the returned values
        var (a, b) = Vals();
        Console.WriteLine(a);
        Console.WriteLine(b);

        // If you only want a subset of the returned values,
        // you can use the discard pattern (_)
        var (_, c) = Vals();
        Console.WriteLine(c);
    }
}

To run the program, save it as MultipleReturnValues.cs and use the dotnet command:

$ dotnet run MultipleReturnValues.cs
3
7
7

In C#, tuples provide a simple way to return multiple values from a method without the need to define a separate class or struct. The syntax (int, int) in the method signature indicates that the method returns two integers.

When calling a method that returns a tuple, you can use tuple deconstruction to easily assign the returned values to separate variables. If you’re only interested in some of the returned values, you can use the discard pattern (_) to ignore the others.

This approach offers a clean and efficient way to handle multiple return values in C#, similar to the idiomatic usage in other languages.

Tuple return types and deconstruction are powerful features in C# that enhance code readability and reduce the need for out parameters or custom classes for simple data structures.