Monday, September 12, 2011

Tuples in Dotnet 4.0

Tuple is introduced with dotnet framework 4.0. Tuples are generic classes which hold values of different types. Tuple can store unlimited number of values. Each value has implemented as read only properties called Item1, Item2, Item3 and so on.

Let’s see how to use Tuple,

//Creating Tuple using constructor
Tuple<string, string, int> t1 = new Tuple<string, string, int>("Mitesh", "Sureja", 29);

//Creating Tuple using static method
Tuple<string, string, int> t1 = Tuple.Create("Mitesh", "Sureja", 29);

Console.WriteLine(t1.Item1); // Output - "Mitesh"
Console.WriteLine(t1.Item2); // Output - "Sureja"
Console.WriteLine(t1.Item3); // Output - 29

Each item in Tuple is statically typed so while using those items don’t need to cast. So instead of using object array and doing boxing and unboxing you can easily use Tuple in that scenario.

Initially Tuple constructor accepts only 8 arguments and the 8th argument (last argument) accepts Tuple type so in last argument we can add new Tuple with more 8 arguments. You can say nested Tuples. Let’s have a look on below code snippet.

Tuple<int, int, int, int, int, int, int, Tuple<int, int, int, int, int>> tn =
new Tuple<int, int, int, int, int, int, int, Tuple<int, int, int, int,int>> (1,2,3,4,5,6,7, new Tuple<int,int,int,int,int>(8,9,10,11,12));

Console.WriteLine(tn.Item6); // Output - 6
Console.WriteLine(tn.Item7); // Output - 7
Console.WriteLine(tn.Rest.Item1); // Output - 8
Console.WriteLine(tn.Rest.Item2); // Output - 9

As shown in above code, the 8th item you can access using Rest.Item1 , Rest.Item2 and so on.

Tuples are more convenient when you want to return multiple values from methods instead list or collection.

Hope you like this new feature of Dotnet framework4.0 and keep using it in daily practice.

See also

No comments:

Post a Comment