How to use Tuple in c# 4.0

The Tuple is new in c# 4.0. Tuple provides way to group elements of disparate data type together. The Tuple is not new, it is just new to C#. It is already present in language like Python and F#. In Python a Tuple storing name and age is something like:

t  = "Mike", 35

And in F# it will look like:

let data = ("Mike",35)

To create Tuple in c# you can use new keyword or you can use Tuple.Create method.

 

var t1 = new Tuple<string, int>("Mike", 35);

var t2 = Tuple.Create("Mike", 35);



The static class Tuple provides 8 overloads Create methods to create Tuple of size 1 to 8.

Using Create method you can create Tuple with maximum 8 elements, but using new keyword you can create Tuple having 8 or more element.
 

 

var t1 = Tuple.Create(1, 2, 3, 4, 5, 6, 7, new Tuple<int, int>(8, 9)); 

Console.WriteLine("Tuple with 8 elements :" + t1);  

var t2 = new Tuple<int,int,int,int, int,int,int,Tuple<int,int>> (1, 2, 3, 4, 5, 6, 7,  new Tuple<int, int>(8, 9));  

Console.WriteLine("Tuple with 9 elements :" + t2);

Output:

tuple_sample.jpg 

You can create nested Tuple like:

 

 var t1 = Tuple.Create("Mike", 35, new Tuple<string, string>("PA", "West Chester"));

If you want to access particular item of Tuple, you can access it using ItemN property, where N is the position of the item.

 

 var t1 = new Tuple<string, int>("Mike", 35);

 string name = t1.Item1; 
int age = t1.Item2;

 

You can iterate through Tuple because this is not a collection. This is more like anonymous class with anonymous properties. Sometimes we create class just to store temporary data, Tuple can be useful in this scenarios.  Also Tuple is often used to return multiple values from function when you don't want to create type.

Ebook Download
View all
Learn
View all