C# 7.0 adds a number of new features and brings the focus on data consumption, code simplification and performance. Perhaps the most interesting feature is tuples, a finite ordered list of values, of possibly different types, which is used to bundle related values together without having to create a specific type to hold them.

Tuples are very good for performance reasons, as you don’t have to store a tuple as an instantiated class to use it, and, in case you want a function to return a tuple, you can return one via tuple literal. It’s up to the caller to decide whether to use the tuple or store it.

In C# 7.0 tuples are value types and their elements are simply public mutable fields. They have value equality, meaning that two tuples are equal (same hash code) if all their elements are pairwise equal.

The main difference between Tuple and ValueTuple are:

  • System.ValueTuple is a value type (struct), while System.Tuple is a reference type (class). Important when talking about allocations and GC pressure.
  • System.ValueTuple is mutable struct, so you need to be extra careful when using them.
  • System.ValueTuple exposes its items via fields instead of properties.

Using C# 7.0 Tuples

Although most C# 7.0 features are available when you create a new project in VS 2017, if you target a framework that does not include those types, you need to add Tuple support via NuGet by downloading `System.ValueTuple` package:

C# 7.0 Support

In Visual Studio, in order to set the language support to C# 7.0 (in VS 2017 default is C# 7.0), you may need to follow the steps below:

  1. right-click on your project name and from the context menu select Properties
  2. inside the Project property window, select Build in the side menu, then
  3. click on Advanced… button at the bottom of the page,
  4. from Advanced Build Settings popup window, select language version: C# 7.0

Error CS1617: Invalid option ‘7’ for /langversion

When you try to build your project after language version change, you may come across the following error:

[box type=”warning” width=”100%” ]Error CS1617 Invalid option ‘7’ for /langversion; must be ISO-1, ISO-2, Default or an integer in range 1 to 6.[/box]

To solve this issue, you need to install the latest version of Microsoft.Net.Compilers package, by running the following command:

Install-Package Microsoft.Net.Compilers

Categorized in:

Tagged in: