C# Tuple

I have recently found this C# feature and found it interesting, let’s take a look.

C# tuples are types that you define using a lightweight syntax. Basically, it gives you the opportunity to define data structures with multiple fields without the complexity of using classes.

Please look at the following example.

(string, int) tuple = ("Hello", 1);
Console.WriteLine($"Tuple with elements {tuple.Item1} and {tuple.Item2}.");
// Output:
// Tuple with elements Hello and 1.

Optionally, you can define the field names.

(string Text, int Count) tuple = ("Hello", 1);
Console.WriteLine($"Tuple with elements {tuple.Text} and {tuple.Count}.");
// Output:
// Tuple with elements Hello and 1.

Another interesting feature of tuples is the support for equality operators.

(string Text, int Count) left = ("Hello", 1);
(string Text, int Count) right = ("Hello", 1);
Console.WriteLine(left == right);
// Output:
// True

Also, you can assign tuples to each other. Keep in mind that tuples must have the same number of fields and the values must be implicitly converted.

(int, double) tuple1 = (17, 3.14);
(double First, double Second) tuple2 = (0.0, 1.0);
tuple2 = tuple1;
Console.WriteLine($"{nameof(tuple2)}: {tuple2.First} and {tuple2.Second}");
// Output:
// tuple2: 17 and 3.14

Now, I must say that you should not go crazy with tuples; replacing separate classes with tuples because you will save a few lines of code it is not a good idea, so before implementing tuples in your code base make sure to document their usage for scenarios where they could be helpful without sacrificing your code quality.

A tiny overview at tuples, but share your thoughts.

For more information about tuples visit Tuple types – C# reference | Microsoft Docs.