Mastering Tuples and Deconstruction in C#
Mastering Tuples and Deconstruction in C# In C#, when you want to return more than one value from a method or unpack multiple values into variables elegantly, tuples and deconstruction come to the rescue. What is a Tuple? A Tuple is a data structure that groups multiple values into a single object. var oldTuple = Tuple.Create("John", 25); Console.WriteLine(oldTuple.Item1); // John Console.WriteLine(oldTuple.Item2); // 25 But the Item1, Item2 naming isn’t very readable. That’s why C# 7.0 introduced ValueTuple with better syntax: var newTuple = ("John", 25); Console.WriteLine(newTuple.Item1); // John Even better, you can name the fields: var person = (Name: "John", Age: 25); Console.WriteLine(person.Name); // John Deconstruction: Unpack with Style Tuples can be deconstructed into separate variables. (string name, int age) = ("Alice", 30); Console.WriteLine(name); // Alice Consol...