A tuple is a data structure that has a specific number and
sequence of elements. An example of a tuple is a data structure with three
elements (known as a 3-tuple or triple) that is used to store an identifier
such as a person's name in the first element, a last name in the second
element, and the person's age in the third element. The .NET Framework directly
supports tuples with one to seven elements. In addition, you can create tuples
of eight or more elements by nesting tuple objects in the Rest property
of a Tuple<T1, T2, T3, T4, T5, T6, T7, TRest> object.
Tuples are commonly used in four ways:
- To
provide easy access to, and manipulation of, a data set.
- To
represent a single set of data. For example, a tuple can represent a
database record, and its components can represent individual fields of the
record.
- To
pass multiple values to a method through a single parameter. For example,
the Thread.Start(Object) method has a single parameter that lets
you supply one value to the method that the thread executes at startup
time. If you supply a Tuple<T1, T2, T3> object as the
method argument, you can supply the thread’s startup routine with three
items of data.
- To
return multiple values from a method without using out parameters
(in C#) or ByRef parameters (in Visual Basic).
The Tuple class does not itself represent a
tuple. Instead, it is a factory class that provides static methods for creating
instances of the tuple types that are supported by the .NET Framework. It
provides helper methods that you can call to instantiate tuple objects without
having to explicitly specify the type of each tuple component.
Let’s see how to use Tuple,
//Creating Tuple using
constructor
Tuple<string, string, int> t1 = new Tuple<string, string, int>("Kalpesh","Patolia", 27);
//Creating Tuple using
static method
Tuple<string, string, int> t1 = Tuple.Create("Kalpesh", "Patolia", 27);
Console.WriteLine(t1.Item1); //
Output - "Kalpesh"
Console.WriteLine(t1.Item2); //
Output - "Patolia"
Console.WriteLine(t1.Item3); //
Output - 27
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.
For more information refer the MSDN http://msdn.microsoft.com/en-us/library/system.tuple.aspx
No comments:
Post a Comment