This site uses cookies to deliver our services. By using this site, you acknowledge that you have read and understand our Cookie and Privacy policy. Your use of Kontext website is subject to this policy. Allow Cookies and Dismiss

Tuples in C# (4.x, 7.0, 7.1)

195 views 0 comments last modified about 9 months ago Raymond Tang

C#

What is a tuple?

Tuple is an ordered sequence, fixed-size, immutable and of heterogeneous objects. Tuple has been existing in other languages such as F#, Python, Perl and etc. for a long time. It was first introduced into C# from C# 4.0 and has been evolving over time. Since C# 7.1, tuple has become very easy to use compared with previous version.

Create a tuple is more efficient and more productive:

  • Save the work of authoring a struct or class that defining the types returned.
  • No need to create a new type.

Tuple in .NET 4.x

Tuple class

Tuple class has 8 methods to create tuples from 1-tuple (singleton) to 8-tuple (octuple). Tuple inherits from object.

Create<T1>(T1)

Create<T1,T2>(T1,T2)

Create<T1,T2,T3>(T1,T2,T3)

Create<T1,T2,T3,T4>(T1,T2,T3,T4)

Create<T1,T2,T3,T4,T5>(T1,T2,T3,T4,T5)

Create<T1,T2,T3,T4,T5,T6>(T1,T2,T3,T4,T5,T6)

Create<T1,T2,T3,T4,T5,T6,T7>(T1,T2,T3,T4,T5,T6,T7)

Create<T1,T2,T3,T4,T5,T6,T7,T8>(T1,T2,T3,T4,T5,T6,T7,T8)

In the exetension methods, you can also construct and deconstruct tuples up to a 18-tuple.

Examples

The following example instantiated a tuple through two

using System;

namespace TestConsoleApp
{
     class Program
     {
         static void Main(string[] args)
         {
             // Instantiate tuple through constructor
             var tupleExample1 = new Tuple<int, string, bool>(1, "Tuple example 1", true);
             Console.WriteLine($"Tuple#:{tupleExample1.Item1}\r\nTuple Name: {tupleExample1.Item2}\r\nBool Value: {tupleExample1.Item3}");

            // Instantiate tuple through Create method
             var tupleExample2 = Tuple.Create(2, "Tuple example 2", false);
             Console.WriteLine($"Tuple#:{tupleExample2.Item1}\r\nTuple Name: {tupleExample2.Item2}\r\nBool Value: {tupleExample2.Item3}");

            // Deconstruct a tuple into variables
             tupleExample1.Deconstruct(out int item1, out string item2, out bool item3);
             Console.WriteLine($"Tuple#:{item1}\r\nTuple Name: {item2}\r\nBool Value: {item3}");
             Console.ReadLine();
         }
     }
}

The output:

image

Tuple in C# 7.x

In the previous version, tuple is supported via a class without language support. The new tuples features require the ValueTuple types. You must add the NuGet package System.ValueTuple in order to use it on platforms that do not include the types. This is due to the different ship cadence for .NET framework and language compilers.

Easy syntax

using System;

namespace TestConsoleApp
{
     class Program
     {
         static void Main(string[] args)
         {
             TupleInCSharp7();
             Console.ReadLine();
         }

        static void TupleInCSharp7()
         {
             // Creat a tuple by direct assignment
             var tupleExample1 = (1, "Tuple example 1", true);
             Console.WriteLine($"Tuple#:{tupleExample1.Item1}\r\nTuple Name: {tupleExample1.Item2}\r\nBool Value: {tupleExample1.Item3}");

            // Create a tuple that provide semantic names
             (int Num, string Name, bool Flag) tupleExample2 = (2, "Tuple example 2", false);
             Console.WriteLine($"Tuple#:{tupleExample2.Num}\r\nTuple Name: {tupleExample2.Name}\r\nBool Value: {tupleExample2.Flag}");

            // Create a tuple that provides semantic names, the right side names will be ignored.
             (int Num, string Name, bool Flag) tupleExample3 = (num: 2, name: "Tuple example 2", flag: false);
             Console.WriteLine($"Tuple#:{tupleExample3.Num}\r\nTuple Name: {tupleExample3.Name}\r\nBool Value: {tupleExample3.Flag}");

            // Deconstruct
             (int num, string name, bool flag) = tupleExample3;
             Console.WriteLine($"Tuple#:{num}\r\nTuple Name: {name}\r\nBool Value: {flag}");

            // Discards num and flag if only interested in name
             (_, string name2, _) = tupleExample3;
             Console.WriteLine($"Tuple#:-\r\nTuple Name: {name2}\r\nBool Value: -");
         }

Output for the above:

image

Inferred tuple element names

C# 7.1 further enhanced tuple to enable inferred element names in tuple. For example:

var num = 1;
var name = "Tuple in C# 7.1";
var flag = true;
var tuple = (num, name, flag);
Console.WriteLine($"Tuple#:{tuple.num}\r\nTuple Name: {tuple.name}\r\nBool Value: {tuple.flag}");

You will encounter compiler error if your IDE

Error    CS8306    Tuple element name 'flag' is inferred. Please use language version 7.1 or greater to access an element by its inferred name.    TestConsoleApp    F:\Projects\TestProject\TestConsoleApp\Program.cs    15    Active

You can change the build settings if this error happens. The default setting is the major version instead of minor version.

Project->Properties->Build->Advanced->Language Version->C# latest Minor Version

image

Tuple in PowerShell

You can definitely use tuple in PowerShell since you can do it in C#.

Refer to the following blogs for some examples:

https://blogs.technet.microsoft.com/heyscriptingguy/2014/09/02/using-a-tuple-in-powershell/

Related pages

Set AttachDbFilename as Relative Path in .NET Core

316 views   0 comments last modified about 5 months ago

.NET Framework, you can use |DataDirectory| to configure connection string when connecting to SQL Server database file via attach mode: AttachDbFilename=|DataDirectory|\dbname.mdf In .NET Core, you cannot directly set SQL Server Express connec...

View detail

Set AttachDbFilename as Relative Path in .NET Core

316 views   0 comments last modified about 5 months ago

.NET Framework, you can use |DataDirectory| to configure connection string when connecting to SQL Server database file via attach mode: AttachDbFilename=|DataDirectory|\dbname.mdf In .NET Core, you cannot directly set SQL Server Express connec...

View detail

Instantiate a Service in ConfigureServices Method in .NET Core

45 views   0 comments last modified about 5 months ago

.NET Core is built in with dependency injection. Usually method ConfigureServices in Startup class is used to register services in the container. The signature of the method looks like the following: public void ConfigureServices(IServiceC...

View detail

Instantiate a Service in ConfigureServices Method in .NET Core

45 views   0 comments last modified about 5 months ago

.NET Core is built in with dependency injection. Usually method ConfigureServices in Startup class is used to register services in the container. The signature of the method looks like the following: public void ConfigureServices(IServiceC...

View detail

ASP.NET Core 2.1 Error - 'Cyrillic' is not a supported encoding name

279 views   0 comments last modified about 5 months ago

After upgrading to ASP.NET Core 2.1 (.NET Core SDK 2.1.301), you may encounter the following error about encoding: System.ArgumentException &nbsp;&nbsp; HResult=0x80070057 &nbsp;&nbsp; Message='Cyrillic' is not a supported encoding name. For information on defining a custo...

View detail

SQLite in .NET Core with Entity Framework Core

173 views   0 comments last modified about 5 months ago

SQLite is a self-contained and embedded SQL database engine. In .NET Core, Entity Framework Core provides APIs to work with SQLite. This page provides sample code to create a SQLite database using package Microsoft.EntityFrameworkCore.Sqlite . Create sample project ...

View detail

Add comment

Please login first to add comments.  Log in New user?  Register

Comments (0)

No comments yet.