... Skip to content

Advanced Tuple Techniques in C#

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;

https://gist.github.com/fatihdgn/4ee6f2c291d3066d03b9787ce454dc52

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.

https://gist.github.com/fatihdgn/0390aadd6a6c70d89261a142a9100b30

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.

https://gist.github.com/fatihdgn/269e42ee85783fca17734a7d7c3a1a03

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.

https://gist.github.com/fatihdgn/f8fd1077aaf6ab7fa12c3a92b68e9f85

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.