Tuples implicitly support the deconstruction pattern, you can deconstruct a tuple into individual variables.
So, instead of doing this:
var myTuple = ("C#", 23); string name = myTuple.Item1; int age = myTuple.Item2;
you can code as follows:
var myTuple = ("C#", 23); (string name, int age) = myTuple; // Deconstruct the myTuple tuple into // separate variables (name and age). Console.WriteLine (name); Console.WriteLine (age);
The following code shows the difference between tuple deconstruction and tuple declaring.
(string name, int age) = myTuple; // Deconstructing a tuple (string name, int age) myTuple2 = myTuple; // Declaring a new tuple
The following code shows how to deconstruct Tuples returned from a method.
using System; class MainClass/*from w w w . j a va 2 s .c om*/ { static (string, int, char) Test() => ( "C#", 23, 'M'); public static void Main(string[] args) { var (name, age, sex) = Test(); Console.WriteLine (name); // C# Console.WriteLine (age); // 23 Console.WriteLine (sex); // M } }