How to Use C# 7 Value Tuples in ASP.NET MVC

With the release of Visual Studio 2017, I wanted to use the new Value Tuples that were introduced in C# 7 in a MVC project I was working on. However, I ran into some issues which I discuss below.

Firstly, Value Tuples are included with .Net 4.7, but if the project’s target framework is lower than that, they can still be used by installing the System.ValueTuple nuget package.

image thumb How to Use C# 7 Value Tuples in ASP.NET MVC

After either using .Net 4.7 or installing the nuget package, when attempting to use Value Tuples you may find that the project fails to build, with no errors in the error log, and errors in the output log like error CS1026: ) expected. This is due to the Microsoft.Net.Compiliers nuget package that is included by default when creating a new MVC project is version 1.3.2. This needs to be updated to at least version 2.0.1.

There is also an error that occurs when using the Value Tuples in Razor views:

The type ‘ValueType’ is defined in an assembly that is not referenced. You must add a reference to assembly ‘System.Runtime, Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a’.
This can be resolved by adding a reference to System.Runtime in the compilation section of the web.config e.g:



However even after fixing this error, the use of Value Tuples in Razor views is still partially limited. Trying to directly set the model of a view to be a Value Tuple or using the new instantiation syntax (e.g. (Name: “John Smith”, Age: 25)) in a Razor view gives a “Feature ‘tuples’ is not available in C# 6.  Please use language version 7 or greater” error.

image thumb 1 How to Use C# 7 Value Tuples in ASP.NET MVC

However, if the tuple is a property of the model, that it can be used without errors.

For an example of how the Value Tuples can be used I have created a small test application. That allows a user to update their current Business Unit.

image thumb 2 How to Use C# 7 Value Tuples in ASP.NET MVC

image thumb 3 How to Use C# 7 Value Tuples in ASP.NET MVC

In this method we are first deconstructing a Value Tuple that has been returned by the GetLoggedInUser method, this allows us to use the results as normal variables since in this case we only need the name. We are also retrieving the users current Business Unit and a List of all Business Units that are returned as Value Tuples.

image thumb 4 How to Use C# 7 Value Tuples in ASP.NET MVC

Here you can see that we can still use the named parameters of the Value Tuples in the view, including the ones in a List. This is much nicer then the Item1… syntax of the regular tuples.

Let’s block ads! (Why?)

Magnetism Solutions Dynamics CRM Blog