DEV Community

Cover image for C# - Use Value Tuples for Multiple Return Values
Keyur Ramoliya
Keyur Ramoliya

Posted on

C# - Use Value Tuples for Multiple Return Values

Value Tuples provide a convenient way to return multiple values from a method without defining custom classes or out parameters.

using System;

class Program
{
    static void Main()
    {
        var (sum, product) = CalculateSumAndProduct(5, 10);

        Console.WriteLine($"Sum: {sum}");
        Console.WriteLine($"Product: {product}");
    }

    static (int Sum, int Product) CalculateSumAndProduct(int a, int b)
    {
        int sum = a + b;
        int product = a * b;

        // Return a Value Tuple with named elements
        return (sum, product);
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example:

  1. We define a CalculateSumAndProduct method that takes two integers as input and calculates their sum and product.

  2. Instead of returning multiple values separately, we return a Value Tuple (int Sum, int Product). Each tuple element has a name (Sum and Product) for improved readability and self-documentation.

  3. In the Main method, we call CalculateSumAndProduct, and by using tuple deconstruction (var (sum, product) = ...), we can easily extract the individual values.

  4. This approach provides a clean and expressive way to return multiple values from a method without introducing custom classes or complex data structures.

  5. Value Tuples are value types, making them efficient and suitable for lightweight data structures.

By effectively using Value Tuples, you can improve the readability and maintainability of your code when you need to return multiple values, and it eliminates the need to create custom classes or use out parameters, resulting in more concise and expressive code.

Top comments (0)