C# – Tuples

  • by
c-sharp-tuple-new-instance-example

C# Tuple

Tuples in C# was introduced in .NET Framework 4.0 and it is available in C# 7.0 and later. Tuples is a Data structure in C# which can hold multiple objects of different data types. This allows us to avoid creating multiple objects for each set of objects for a same data type.

Example of a Tuple in C# and accessing objects:

var modelNumbers = Tuple.Create("TVS Ronin", 310, 350,"BMW G 310 GS", 2.0);
Console.WriteLine(modelNumbers.Item1);
Console.WriteLine(modelNumbers.Item3);

Output:

" modelNumbers = new Tuple<string, int, int, string,double>(

Output:

c-sharp-tuple-new-instance-example

c-sharp-tuple-new-instance-example

Creating Nested Tuple

Tuples can store up to 8 objects inside it. To store more than 8 object inside it we can using nested Tuple. A Tuple can hold another Tuple inside it.

Example of Nested Tuples:

var models = Tuple.Create("TVS Ronin", 310, 350, "BMW G 310 GS",Tuple.Create("Ather 450X Gen 3", "TVS Raider 125", "125", 6), Tuple.Create(3, "Citroen C3"),111);
Console.WriteLine(models.Item4);
Console.WriteLine(models.Item5.Item1);
Console.WriteLine(models.Item6.Item2);
Console.ReadLine();

Output:

c-sharp-nested-tuple-example

c-sharp-nested-tuple-example

The 8th object in a Tuple can be accessed using Rest property

Example:

var models = Tuple.Create("TVS Ronin", 310, 350, "BMW G 310 GS",Tuple.Create("Ather 450X Gen 3", "TVS Raider 125", "125", 6), Tuple.Create(3, "Citroen C3"),111, "Pulsar N160");
Console.WriteLine(models.Rest.Item1);
Console.ReadLine();

Output:

Pulsar N160

Passing Tuple as a Method Parameter:

We can also pass a Tuple to a method.

Example:

static void Main()
{
Example(Tuple.Create("Mark", "Male", 25));
Console.ReadLine();
}

public static void Example(Tuple<string,string,int> info)
{
Console.WriteLine("Name: " + info.Item1);
Console.WriteLine("Gender: " + info.Item2);
Console.WriteLine("Age: " + info.Item3);
}

Output:

c-sharp-tuple-as-a-method-parameter

c-sharp-tuple-as-a-method-parameter

Tuple as Method Return Type:1

Tuple can be also used as a return type of a method.

Example:

static void Main()
{
var info = Example();
Console.WriteLine("Name: " + info.Item1);
Console.WriteLine("Gender: " + info.Item2);
Console.WriteLine("Age: " + info.Item3);
Console.ReadLine();
}

public static Tuple<string, string, int> Example()
{
return Tuple.Create("Mark", "Male", 25);
}

Output:

c-sharp-tuple-as-a-method-parameter

c-sharp-tuple-as-a-return-type


1
Tags: