Return Multiple Values from Method in C#


In this article we are going to discuss about how to return multiple values from method in C#.

How to return more than one value from a method in C#?

You can return multiple values from a method using a List, Arraylist(any collection), tuples or out parameters. In C#, there are several ways to return more than one value from a method. Here are a few common approaches with examples.

1. Tuples

Tuples allow you to return multiple values in a single object.

Example

public (int, int) GetValues()
{
    int a = 5;
    int b = 10;
    return (a, b);
}

static void Main()
{
    var values = GetValues();
    Console.WriteLine($"a: {values.Item1}, b: {values.Item2}"); // Output: a: 5, b: 10
}

2. Out Parameters

The out keyword allows a method to return multiple values by passing parameters by reference.

Example

public void GetValues(out int a, out int b)
{
    a = 5;
    b = 10;
}
static void Main()
{
    int x, y;
    GetValues(out x, out y);
    Console.WriteLine($"x: {x}, y: {y}"); // Output: x: 5, y: 10
}

3. Using a Custom Class

You can define a custom class to hold multiple return values.

Example

public class CalculationResult
{
    public int Sum { get; set; }
    public int Product { get; set; }
}

public class Program
{
    public static CalculationResult Calculate(int a, int b)
    {
        return new CalculationResult
        {
            Sum = a + b,
            Product = a * b
        };
    }

    public static void Main()
    {
        int x = 5;
        int y = 10;
        CalculationResult result = Calculate(x, y);

        Console.WriteLine($"Sum: {result.Sum}, Product: {result.Product}");
    }
}

Prev Next