Posts Tuples in C# 7
Post
Cancel

Tuples in C# 7

Ever had to create a class, just so that you could return more than one data from one particular function! Well, there is a solution. In C#. Tuples, it is. Tuples has been around since .Net Framework 4.0. But it got much better in time, which brings us to the changes in C# 7.0.   Let’s consider a function, which reads the First name and Last name of a user, and has to return them.

  • One way of doing this would be to create a User class and return an object. But, what if you don’t want to create a class.
  • You can use “out” or “ref” parameters in the function. But there are scenarios where this is not an option.
  • Using tuples could help you with this.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
using System;

namespace TupleTrial
{
    class Program
    {
        static void Main(string[] args)
        {
            var name = GetName();

            System.Console.WriteLine($"user is {name.firstName} {name.lastName}");
        }

        static (string firstName, string lastName) GetName()
        {
            var fn = Console.ReadLine();
            var ln = Console.ReadLine();

            return (fn, ln);
        }
    }
}

As you can see, we return firstName and lastName from the function, and is used likewise in the calling function.   There is one catch though. At the time of writing this blog, the above given code will throw a compile time error, saying "error CS8179: Predefined type 'System.ValueTuple2' is not defined or imported" or "error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found."

To fix this :

  • If you are using Visual Studio :

Install the Nuget package System.ValueTuple, or go to Package Manager Console and run

Install-Package System.ValueTuple -Version 4.3.1

  • If you are using Visual Studio Code :

Open Terminal in Visual Studio Code and run

dotnet add package System.ValueTuple

Note that, this could be run from powershell or cmd as well, if you are already in the project folder.   This is a work-around for this issue as of now, and I believe, that the .Net team will get this working without having to install this package, soon.   You can find an example for the same here on GitHub. References : Microsoft Docs, CodeProject

This post is licensed under CC BY 4.0 by the author.