9/13/2023 3:48:35 PM

If you are like me, you love named Tuples but you quickly forget how to instantiate them (with brackets like in JavaScript?). Below is a quick set of reminders on how to instantiate them and other Tuples. Note that the first two examples are using the older Tuple class while the rest are using the newer TupleValue struct. The TupleValue allows for field names and are much easier to work with.

public void Tuple_Exmples() { //System.Tuple - Reference Type var person_01 = new Tuple<string, string>("John", "Doe"); Console.WriteLine(person_01.Item1 + " " + person_01.Item2); //System.Tuple - Reference Type var person_02 = Tuple.Create("John", "Doe"); Console.WriteLine(person_02.Item1 + " " + person_02.Item2); //System.ValueTuple - Value Type var person_03 = ValueTuple.Create("John", "Doe"); Console.WriteLine(person_03.Item1 + " " + person_03.Item2); //System.ValueTuple - Value Type (string, string) person_04 = ("John", "Doe"); Console.WriteLine(person_04.Item1 + " " + person_04.Item2); //System.ValueTuple - Value Type var person_05 = ("John", "Doe"); Console.WriteLine(person_05.Item1 + " " + person_05.Item2); //named tuple //System.ValueTuple - Value Type (string FirstName, string LastName) person_06 = ("John", "Doe"); Console.WriteLine(person_06.FirstName + " " + person_06.LastName); //named tuple //System.ValueTuple - Value Type var person_07 = (FirstName: "John", LastName: "Doe"); Console.WriteLine(person_07.FirstName + " " + person_07.LastName); //list of named tuples //System.ValueTuple - Value Type var people_01 = new List<(string FirstName, string LastName)>(); people_01.Add((FirstName: "John1", LastName: "Doe1")); people_01.Add(("John2", "Doe2")); people_01.Add(("John3", "Doe3")); foreach (var person in people_01) { Console.WriteLine(person.FirstName + " " + person.LastName); } }