Patrick Wambugu
rickwag's blog

rickwag's blog

C#: How to Return Multiple Values from a Method

Photo by Joshua Sortino on Unsplash

C#: How to Return Multiple Values from a Method

The out keyword vs tuples

Patrick Wambugu's photo
Patrick Wambugu
·Dec 4, 2021·

2 min read


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}");

//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}");

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

That's it!!


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)


Share this