Who uses tuples? No? Well, I can’t say I really use them either. But that’s likely to change in c#8. Once I get my whole team over to vs2019 and migrate our code over to dotnet core 3 we can move to c#8. There are language changes in c#8 that are built upon the changes to tuples that were introduced in c#7. So tuples could become a regular occurrence in our code quite soon. So I’m going to give a brief primer on tuples as they exist in C#7.
Here is an example...
using System;
namespace MyConsoleApp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello Stackathon readers!");
var dimensions = getDimensions();
Console.WriteLine($"Width is {dimensions.width}");
Console.WriteLine($"Height is {dimensions.height}");
Console.WriteLine($"Depth is {dimensions.depth}");
Console.Read();
}
private static (double width, double height, double depth) getDimensions()
{
return (2.3, 10.4, 4.6);
}
}
}
Our dimensions variable in Main() is a tuple. The variable has properties for width, height and depth which are available in intellisense. We can think of it as a lightweight object that saves us the effort of defining a class or struct.
We can also deconstruct our tuple into a new tuple like so...
(double width, double height, double depth) localTuple = getDimensions();
But be aware that the order of your tuple fields is import here - it's mapped by position. If you switch height and width, the mapping will be wrong. Better to just use a var.
var dimensions = getDimensions();
We can also do the following to give us three local variables with values from the tuple returned by getDimensions().
var (w, h, d) = getDimensions();
This may not seem earth shattering. But this syntax was needed by some new features coming in C#8. Specifically in the area of pattern matching. More on that another time.
Top comments (1)
"But be aware that the order of your tuple fields is import here - it's mapped by position. If you switch height and width, the mapping will be wrong. Better to just use a var." Words to live by :-)
Personally, I hated System.Tuple because of the ugly
Item1...Item2...Itemn
properties, but I really like value tuples because they properties are named. Now I read that deconstructing them is position based and I'm starting to think to myself: Where in my code base there are tuple deconstruction? Luckily, The answer is "Almost nowhere".Does this mean I'm going to stop using value tuples? Hell no. but I am going to be extra careful about deconstructing them in the future.
Thanks for your post, I've learned something new today!