Designing and coding

Menu

Tag Archives: Tuple

Tuples are one of the awesome features of C# which was initially introduced with .NET 4.0. Although it is less used but it become very handy when we need to return multiple values from a function. We have another option to use out operator but it is not recommended due to various reasons. I am not going to discuss it in this post. Tuple is a static class under namespace System which implements a Factory pattern to create the instances of Tuples. It has a Create method with eight overloads which allows us to have 8 elements in a Tuple. Also, we can have nested tuples as well.

There were few issues with System.Tuple. It is a reference type so even if you are returning few values type elements , the instance gets created on heap, means adding pressure on Garbage Collector. It doesn’t allow to provide a name to the elements, instead we have to refer it as item1, item2.. etc. Also, the way we used to create Tuple is also quite verbose.

Tuple in C# 7.0

C# 7.0 introduces System.ValueTuple as a new language feature, which resolves the problems mentioned above and provides few more additional features. And Yes, it has the power of Value Type so it removes the GC overhead of the old tuple.

Note: ValueTuple is available as indepedent nuget package. You can install it from here.

Lets see few examples of new Value Tuples,

Tuple Literals

Tuple literal is a comma separated list of literal (of various types), surrounded by parenthesis.