Tuesday 26 June 2012

.Net Tips : New Tuple class in .Net Framework 4

The .NET Framework 4 introduce the System.Tuple class for creating tuple objects that contain structured data. It also provides generic tuple classes to support tuples that have from one to eight components . To support tuple objects that have more than 8 components, there is a generic tuple class with seven type parameters and an eighth parameter of any tuple type. Tuple Class provides static methods for creating tuple objects.You can store upto eight types of value in one tuple object. This tuple object may useful for .Net Beginners to .Net Expert Level people.

Here is table for this.

Name Description
Create(T1) Creates a new 1-tuple, or singleton.
Create(T1, T2) Creates a new 2-tuple, or pair.
Create(T1, T2, T3) Creates a new 3-tuple, or triple.
Create(T1, T2, T3, T4) Creates a new 4-tuple, or quadruple.
Create(T1, T2, T3, T4, T5) Creates a new 5-tuple, or quintuple.
Create(T1, T2, T3, T4, T5, T6) Creates a new 6-tuple, or sextuple.
Create(T1, T2, T3, T4, T5, T6, T7) Creates a new 7-tuple, or septuple.
Create(T1, T2, T3, T4, T5, T6, T7, T8) Creates a new 8-tuple, or octuple.

Tuples are mostly use for following ways.
  • Return multiple values from a method without using out parameters (in C#) or ByRef parameters (in Visual Basic). 
  • Easy access of the data. 
  • To pass multiple values to a method through a single parameter. 
  • Store multiple values in sing object.

Here is example of this.
In this example we take four values in tuple , first is firstname , second is lastname , third is salary , and forth is mobilenumber. We can store this four values in single object. This is the benefit of tuple class.

C# Example :
 var objTupe = new System.Tuple<string, string, double, long>("Mike","Anderson",29000,9999999999);
 Response.Write("Item1 : " + objTupe.Item1);
 Response.Write("<br/>Item2 : " + objTupe.Item2);
 Response.Write("<br/>Item3 : " + objTupe.Item3);
 Response.Write("<br/>Item4 : " + objTupe.Item4);

VB.net Example :
 Dim objTupe = New System.Tuple(Of String, String, Double, Long)("Mike", "Anderson", 29000, 9999999999L)
 Response.Write("Item1 : " & objTupe.Item1)
 Response.Write("<br/>Item2 : " & objTupe.Item2)
 Response.Write("<br/>Item3 : " & objTupe.Item3)
 Response.Write("<br/>Item4 : " & objTupe.Item4)

Output :



You can access the individual tuple value by using tuple object's property like Item1 ,Item2 , Item3 , Item4 etc... These property available depends on how many parameters you taken in tuple object at object creation time , we took 4 parameters so we got these 4 properties.

This type of C# Tips is very useful in day to day programming life.

Note : Give Us your valuable feedback in comments. Give your suggestions in this article so we can update our articles accordingly that.


No comments:

Post a Comment