Tuples

2023-02-08 C# Tuples

Tuple is lightweight data structure to put together some heterogenous items. Original ways to create them with old C# was something like this

var tuple = Tuple.Create(1, "Hello", 3);
Console.WriteLine(tuple);
Console.WriteLine(tuple.Item1);

One problem was that all items of the tuple were called ItemNNN and it was hard to deduce what you stored there in the first place. In C# 7 there were introduced names to tuple items. There are two ways to build them

var tuple2 = (Number: 1, Name: "Hello", Count: 3);

Or with explicitly specified type

(int Number, string Name, int Count) tuple3 = (1, "Hello", 3);

Named tuples are value type (contrary to original System.Tuple) and they support equality, which compares all items sequentially without considering item name. The tuple is also easy to print and easy to hash, since they have sensible built-in methods available for both.

Usage is simple

Console.WriteLine(tuple2);          // (1, Hello, 3)
Console.WriteLine(tuple2.Number);   // 1
Console.WriteLine(tuple2.Name);     // Hello
Console.WriteLine(tuple2.Count);    // 3
Console.WriteLine($"{tuple2} and {tuple3} are " + (tuple2 == tuple3 ? "the same" : "different"));
                                    // (1, Hello, 3) and (1, Hello, 3) are the same

It is also possible to deconstruct the type into individual fields

(int num, string name, int count) = tuple3;