Working with Tuple in C# 4.0

0 comments
Tuple can store n - number of values in it. The type of each of those variables as generic parameters, and the object will create those values for you.

Using a Tuple

Base class library exposes two objects. It exposes the static class Tuple which allows you to get a number of Tuple instances based on the Static method Create, and a number of Tuple classes, each of which takes some specific number of Generic arguments. 
  • Tuple.Create<t1>
  • Tuple.Create<t1,t2>
  • Tuple.Create<t1,t2,t3>
  • Tuple.Create<t1,t2,t3,t4>
  • Tuple.Create<t1,t2,t3,t4,t5>
  • Tuple.Create<t1,t2,t3,t4,t5,t6>
  • Tuple.Create<t1,t2,t3,t4,t5,t6,t7>
  • Tuple.Create<t1,t2,t3,t4,t5,t6,t7,t8>
Tuple.Create has 8 overloads and each of these overloads returns new object of Tuple<t1, t2...t8> class.  So .NET framework exposes 8 different classes each of them taking T1..... T8number of arguments and each of them exposes Item1..... Item8 number of arguments. 


The Tuple class can be instantiated directly as well without using static objects. Even If you see in Reflector, all the Create method actually returns its respective Tuple object.  


Hence, lets create object of Tuple. 
Tuple<int, string> tuple = new Tuple<int, string>(20, "Csharp");


Here the class with two Generic Type argument is created and hence it exposes the items as Item1 and Item2. 
Similar to this, you can also create Tuple of 3, 4, 5 .....7 types  


How to generate N number of argument list?


Tuple actually supports more than 8 argument as it expects the 8th argument as another Tuple. Say for instance, if you write : 
Tuple<int, string,int,int,int,int,int,int> tuple = new Tuple<int, string,int,int,int,int,int,int>(20, "Csharp", 39, 39,59,49,30, 33);


You will eventually end up with an ArgumentException.


Hence the appropriate call to it must be :
Tuple<int, string,int,int,int,int,int,tuple<int>> tuple = new Tuple<int, string,int,int,int,int,int,tuple<int>>(20, "Csharp", 39, 39,59,49,30, new Tuple<int>(33));


So you can see the last generic argument we pass as Tuple. Using this argument you can create as many arguments as you want. 


READ MORE >>

0 comments: