Tuples
System.ValueTuple
is modern; System.Tuple
is legacy.
Tuple
public (string, int) GetFruit()
{
return ("Apples", 5)
}
var fruit = GetFruit();
The tuple’s fields are automatically named Item1 and Item2:
fruit.Item1 // returns "Apples"
fruit.Item2 // returns 5
Tuple with Named Fields
public (string Name, int Qty) GetNamedFruit()
{
return (Name: "Apples", Qty: 5);
}
var namedFruit = GetNamedFruit();
namedFruit.Name // returns "Apples"
namedFruit.Qty // returns 5
Tuple Deconstruction
(type v1, type v2, …) = function();
… or …
var (v1, v2, …) = function();
… or …
type var1 = val1;
type var2 = val2;
(var1, var2) = function();
It is now possible to assign values to an existing variable and initialize newly declared variables in the same deconstruction:
int x = 0;
(x, int y) = point;
Example
Store return value in a tuple with two named fields:
(string FruitName, int FruitQty) myFruit = GetNamedFruit();
Console.WriteLine(myFruit.FruitName); // output: "Apples"
Console.WriteLine(myFruit.FruitQty); // output: 5
Deconstruct the return value into two separate variables:
(string name, int num) = GetNamedFruit();
Console.WriteLine(name); // output: "Apples"
Console.WriteLine(num); // output: 5