What is tuple and when it was introduced?
A
tuple is a new data type introduced by .NET Framework 4.0. When there is a
requirement to store the multiple values
of different data types and without having to create a class to store the
values, we can go with tuple. Simply “Tuple
is a container with the similar or different data type, which supports 7 items
(similar/different data types) plus 1 Tuple type”. Point to be noted here
is, it is not a collection.
How
to declare a tuple?
Tuple
will be declared similar to Dictionary<Tkey, TValue>.
Tuple<T1>
Tuple<T1, T2>
Tuple<T1, T2, T3>
Tuple<T1, T2, T3, T4>
Tuple<T1, T2, T3, T4, T5>
Tuple<T1, T2, T3, T4, T5, T6>
Tuple<T1, T2, T3, T4, T5, T6, T7>
Tuple<T1, T2, T3, T4, T5, T6, T7, TRest>
Tuple<T1, T2>
Tuple<T1, T2, T3>
Tuple<T1, T2, T3, T4>
Tuple<T1, T2, T3, T4, T5>
Tuple<T1, T2, T3, T4, T5, T6>
Tuple<T1, T2, T3, T4, T5, T6, T7>
Tuple<T1, T2, T3, T4, T5, T6, T7, TRest>
Here,
T can be any type and TRest is a Tuple type.
If
you have seen it, while declaring a tuple, you will get 8 override functions,
as shown below.
In the last override
method, we can add 7 types with one Tuple type (I will explain in detail with
an example).
The
method given above will return all the arithmetic results of the provided
values (a, b).
How to read tuple
Once
you have added values into tuple, it is easy to retrieve the data from it.
Tuple stores the data in “Item” property. From the example given above, we can
get the values, as shown below.
A
Tuple with more than 7 arguments.
The
8th type of a tuple is
tuple.
Observe
the example given below. We have a tuple called dataWithEightarguments with 8
parameters in which 8th one is a tuple. Hence, while adding data to it, we need
to pass tuple type data as 8th parameter.
No comments:
Post a Comment