A tuple is an ordered, finite list of elements. Tuples are commonly used in programming as a means to work with one single entity collectively instead of individually working with each of the tuple’s elements, and to represent individual rows (ie. “records”) in a relational database.
In C# 7.0, methods can have multiple return values. Behind the scenes, the compiler will use the new ValueTuple struct.
public (int sum, int count) GetTallies()
{
return (1, 2);
}
Side note: for this to work in Visual Studio 2017, you need to get the System.ValueTuple
package.
If a tuple-returning method result is assigned to a single variable you can access the members by their defined names on the method signature:
var result = GetTallies();
// > result.sum
// 1
// > result.count
// 2
Tuple deconstruction separates a tuple into its parts.
For example, invoking GetTallies
and assigning the return value to two separate variables deconstructs the tuple into those two variables:
(int tallyOne, int tallyTwo) = GetTallies();
var
also works:
(var s, var c) = GetTallies();
You can also use shorter syntax, with var
outside of ()
:
var (s, c) = GetTallies();
You can also deconstruct into existing variables:
int s, c;
(s, c) = GetTallies();
Swapping is now much simpler (no temp variable needed):
(b, a) = (a, b);
Interestingly, any object can be deconstructed by defining a Deconstruct
method in the class: