Friday, June 19, 2026

C# Example of ValueTuple as method return type

A method can return multiple values. Here is an example of ValueTuple as Method Return Type that returns multiple values.

class Demo
{
    static (int Sum, int Product) Calculate(int a, int b)
    {
        return (a + b, a * b);
    }
    static void Main()
    {
        var result = Calculate(10, 20);
        Console.WriteLine(result.Sum);
        Console.WriteLine(result.Product);
    }
}

Output

30

200

Note. You can deconstruct:

(int sum, int product) = Calculate(10, 20);
Console.WriteLine(sum);
Console.WriteLine(product);

Alter. You can write above Calculate method in following ways also.
class Demo
{
    static (int, int) Calculate(int a, int b)
    {
        return (a + b, a * b);
    }

    static void Main()
    {
        var result = Calculate(10, 20);

        Console.WriteLine(result.Item1);
        Console.WriteLine(result.Item2);
    }
}

No comments:

Post a Comment

Hot Topics