Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to return Tuple from a method using Visual Studio 2017 and C# 7.0

I've installed Visual Studio 2017 Community that was released a week ago, and I started exploring the new features of C# 7.

So I created a simple method that returns two values:

public class Program
{
    public static void Main(string[] args)
    {
        (int sum, int count) a = ReturnTwoValues();
    }

    static (int sum, int count) ReturnTwoValues() => (1, 1);
}

Compiler is generating an error:

Error CS8137 Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference?

I tried finding a reference in the framework with this name, but with no luck !

If we need additional stuff to use C# 7.0 features, then it is very weird that we need to do that for every project ?!

like image 226
Zein Makki Avatar asked Nov 27 '16 07:11

Zein Makki


People also ask

Is tuple immutable c#?

Tuple types are immutable. Data members of System. ValueTuple types are fields.

What is System ValueTuple?

ValueTuple is a structure introduced in C# 7.0 which represents the value type Tuple. It is already included in . NET Framework 4.7 or higher version. It allows you to store a data set which contains multiple values that may or may not be related to each other.

What is the advantage of tuple as returning function argument?

Tuples provide a third way of returning multiple function values, one that combines aspects of the structure-based and on-the-fly options already mentioned. With tuples, you define the values to be returned as part of the function declaration, a bit like the out-parameter variation.


3 Answers

I Just ran through this page on Roslyn which describes the following steps to get this working:

  1. Start a C# project
  2. Add a reference to the System.ValueTuple package from NuGet (pre-release)

enter image description here

Following those steps, it is now working. But it is really very weird that we need to do that for every single project that we start! Hope this is fixed when we reach the Official release!

like image 157
Zein Makki Avatar answered Oct 20 '22 08:10

Zein Makki


I started getting this error after I installed .Net 4.7 Framework, and changed my project to target .Net 4.7

ValueTuple is now included with .Net 4.7, so you don't have to reference the ValueTuple manually.

All I had to do to correct the compile error was remove the reference to System.ValueTuple from my project's references.

like image 69
aaaa bbbb Avatar answered Oct 20 '22 08:10

aaaa bbbb


I got this error too after updating to .NET 4.7.2 and was able to fix it by re-installing nuget packages using:

Update-Package -Reinstall
like image 7
martinoss Avatar answered Oct 20 '22 08:10

martinoss