How to return multiple values in C# 7?

Coder Newbie picture Coder Newbie · Mar 21, 2017 · Viewed 93.7k times · Source

Is it is possible to return multiple values from a method natively?

Answer

Sid picture Sid · Mar 21, 2017

What do you mean by natively?

C# 7 has a new feature that lets you return more than one value from a method thanks to tuple types and tuple literals.

Take the following function for instance:

(string, string, string) MyCoolFunction() // tuple return type
{   
    //...        
    return (firstValue, secondValue, thirdValue);
}

Which can be used like this:

var values = MyCoolFunction();
var firstValue = values.Item1;
var secondValue = values.Item2;
var thirdValue = values.Item3;

Or by using deconstruction syntax

(string first, string second, string third) = MyCoolFunction();

//...

var (first, second, third) = MyCoolFunction(); //Implicitly Typed Variables

Take some time to check out the Documentation, they have some very good examples (this answer's one are based on them!).