[EN] New features in C# 7.0: Tuples

In the previous post I wrote about out variables and pattern matching in C# 7.0. Today I will focus on another features which are Tuples.

Tuple is not new thing, we have it already in C#, but this time the newest version of C# adds tuple types and tuple literals. With C# 7.0 we can implement method looks like this

GetValues method returns tuple object that contains three fields. Let’s take a look at example

As you can see in GetValues1 method I didn’t specified names for fields, so to get value we need to use default names like Item1, Item2, …, ItemN. We can change it and add our own names for fields. Take a look at the second example of method – GetValues2. In this method I specified field names: Val1, Val2, Val3. When we use this tuple return type we have a hint from IntelliSense with our field names. Item1, Item2, Item3 fields aren’t visible, but we can use it as well and it works.

1

In addition we can assign tuple return type to new local variables, it’s called deconstructing declaration.

If we want to assign result to existing variables we can do it as well.

It’s also good to mention that if you don’t use the latest .NET Framework, but you want to use the newest Tuples, you can do it. Just install the right package from NuGet Packages – System.ValueTuple.