C# 7.0: Tuples

Microsoft has recently unveiled some changes, that developers will be introduced to in the future release of C#, the C# 7.0.

Among all developers who see sharp ūüėĬ†, there is an enormous amount of anticipation of the features in the final release. In the meantime, I decided to interpret you one¬†of them today. So let’s dive¬†into it!

Tuples, I'm ready!
[1]: Tuples, I’m ready!

One of those things, that may please current developers and possibly attract new ones, are tuples. Tuples or tuple-like syntax can be found in many languages.

The universe before C# 7.0

In previous versions of C#, it could have been achieved this way using the out keyword when passing variables as parameters to a method:

This keyword allowed multiple values to be “returned”¬†by the method. I am using apostrophes, because it is not really a tuple case-in-point and the GetTwoValues doesn’t really return any value, as well.

Getting closer…

This example in Python shows tuples the way they are commonly understood.

The example here is pretty straightforward and easy to understand. I personally haven’t been in a position wanting to return two or more values within a method, but is sure a step forward in the versatility of the C# language.

C# 7.0 at last

Let’s finally examine how tuples will look like in C# 7.0.

This sample works the same as the other one with out keywords shown earlier in the article. We get the values as elements in a tuple, store them into a variable of unknown type and then print them to the console. Each value is stored in the resulting container as an element called Item1 (Item2, Item3 and so on).

Item1 and Item2 is not overly descriptive. To avoid this woe, we can make use of named tuple elements. Let’s edit our code a bit.

The only, but important, change here is the switch from Item1 and Item2 to First and Second. Hence, making our code far more readible.

What do you think about C# 7.0 and tuples? Leave a comment down below.

Source: MSDN

Leave a Reply

Your email address will not be published. Required fields are marked *