C#: How to Return Multiple Values from a Method

The out keyword vs tuples

Intro

You wanna return more than one value from a method? You don't want to do some hack like returning a list? Well here are two ways you can easily answer these two questions.

Old School (The out keyword)

Here is how you can use the out keyword to return multiple values from a method...

void GiveMeTwoNumbers(out int firstNumber, out int secondNumber)
{
 firstNumber = 10;
 secondNumber = 20;
}

int numberOne = default;
int numberTwo = default;

Console.WriteLine($"numberOne before => {numberOne}");
Console.WriteLine($"numberTwo before => {numberTwo}");

GiveMeTwoNumbers(out numberOne, out numberTwo);
Console.WriteLine(".........Called GiveMeTwoNumbers Method.............");

Console.WriteLine($"numberOne after => {numberOne}");
Console.WriteLine($"numberTwo after => {numberTwo}");

//results
//numberOne before => 0
//numberTwo before => 0
//.........Called GiveMeTwoNumbers Method.............
//numberOne after => 10
//numberTwo after => 20

There you go, just make sure you use the out keyword in both the method defination and method call, for this to work.

Other School (tuples)

And here is how you can use tuples to achieve the same goal...

(int, int) GiveMeTwoNumbers()
{
 var firstNumber = 10;
 var secondNumber = 20;

 return (firstNumber, secondNumber);
}

(int numberOne, int numberTwo) = GiveMeTwoNumbers();

Console.WriteLine($"numberOne => {numberOne}");
Console.WriteLine($"numberTwo => {numberTwo}");

//results
//numberOne => 10
//numberTwo => 20

That's it!!

Conclusion

Now the ball is on your side, pick one way(whichever you prefer) and roll with it.

To learn more about the out keyword check out the docs here(out keyword). To learn more about tuples check out the docs here(tuples)

Thanks😁