Monday, October 10, 2016

Tuples has been there since the release of .NET 4.0 and it was mostly used for returning more than one value from a method. With C# 7.0, there are couple of new improvements coming around Tuples. Let’s see what those are.

So what's not so good with this? First you need to create a new instance of a Tuple before returning. Then you can’t name the single elements, thus you are limited to access the returned elements by Item1, Item2 etc.

Here you can specify the names for the individual elements inside the returning Tuple and no object creation is needed. If you are comfortable with no names, you can still omit the names and access elements by Item1, Item2 etc.

static (int, int, int) GetValues(List<int> numbers)

{

return (numbers.Min(), numbers.Max(), numbers.Sum());

}

Or you can always me more specific.

static (int min, int max, int sum) GetValues(List<int> numbers)

{

return (min: numbers.Min(), max: numbers.Max(), sum: numbers.Sum());

}

You can even use some other names when you are declaring the Tuple and doing the deconstruction.