Advanced Tuple Techniques in C#

Tuple in C# was introduced at C# 4 but it was nothing like what some other languages has to offer. It was clunky and hard to use. The only thing they provided us in C# was a couple of generic classes and nothing more. But it is history now because as of C# 7, they are massively improved and have a first class support in the language. Today we are going to take a look at how to use them and after that I will show you some techniques on how to use them more 🙂

First, how to use them;

So, if we are on the same level now, we can get in to the juicy details.

Add deconstruct support to your classes

Actually this one is not entirely related to tuples but makes sense afterwards. You can add a method called “Deconstruct” in your classes and imitate how tuples deconstruct itself.

Add implicit operator for that tuple to your classes

You can use your newly created tuples in your implicit operators because they are like your any other type. Let’s improve our previous example.

Write extension methods to or for your tuples

When you have no access to specific class or struct and want to add something but don’t want to create something new inheriting that, the answer is always writing an extension method. I heavily use them when I’m coding and I found a way to use them here too. You can write extension methods for the tuples or write something returns one.

So, that’s it for now. Please let me know how you are using the new tuples in C# and I will make sure to add more if I find any other way to use them.

Thanks for tuning in and see you in the next post.