CSharp - Type Creation Tuples Definition

Introduction

Tuples provide a simple way to store a set of values.

You can use tuples to return multiple values from a method without using to out parameters.

Syntax

To create a tuple literal, list the desired values in parentheses.

This way creates a tuple with unnamed elements, which can be referred as Item1, Item2, and so on:

var myTuple = ("C#", 23);    // Allow compiler to infer the element types

Console.WriteLine (myTuple.Item1);   // C#
Console.WriteLine (myTuple.Item2);   // 23

Tuples are value types, with mutable (read/write) elements:

var joe = myTuple;                 // joe is a *copy* of job
joe.Item1 = "Joe";             // Change joe's Item1 from C# to Joe
Console.WriteLine (myTuple);       // (C#, 23)
Console.WriteLine (joe);       // (Joe, 23)

You can specify a tuple type explicitly. Just list each of the element types in parentheses:

(string,int) myTuple  = ("C#", 23);   // var is not compulsory with tuples!

You can return a tuple from a method:

using System;
class MainClass
{
   public static void Main(string[] args)
   {

       (string,int) person = GetPerson();   // Could use 'var' here if we want
       Console.WriteLine (person.Item1);    // C#
       Console.WriteLine (person.Item2);    // 23

   }
   static (string,int) GetPerson() => ("C#", 23);
}

ValueTuple.Create

You can also create tuples via a factory method on the (nongeneric) ValueTuple type:

ValueTuple<string,int> myTuple1 = ValueTuple.Create ("C#", 23);
 (string,int)          myTuple2 = ValueTuple.Create ("C#", 23);

Equality Comparison

ValueTuple<> types override the Equals method to allow equality comparisons to work meaningfully:

var t1 = ("one", 1);
var t2 = ("one", 1);
Console.WriteLine (t1.Equals (t2));    // True

The ValueTuple<> types also implement IComparable, you can use tuples as a sorting key.