Saturday, August 3, 2019

TUPLE

A tuple is a data structure that contains a sequence of elements of different data types. 

It can be used where you want to have a data structure to hold an object with properties, but you don't want to create a separate type for it.


Tuple<T1, T2, T3, T4, T5, T6, T7, TRest>
Tuple<int, string, string> person = 
                        new Tuple <int, string, string>(1, "Steve", "Jobs");


Example: Accessing Tuple Elements
var person = Tuple.Create(1, "Steve", "Jobs");
person.Item1; // returns 1
person.Item2; // returns "Steve"
person.Item3; // returns "Jobs"


var numbers = Tuple.Create("One", 2, 3, "Four", 5, "Six", 7, 8);
numbers.Item1; // returns "One"
numbers.Item2; // returns 2
numbers.Item3; // returns 3
numbers.Item4; // returns "Four"
numbers.Item5; // returns 5
numbers.Item6; // returns "Six"
numbers.Item7; // returns 7
numbers.Rest; // returns (8)
numbers.Rest.Item1; // returns 8


Usage of Tuple

Tuples can be used in the following scenarios:
  1. When you want to return multiple values from a method without using ref or outparameters.
  2. When you want to pass multiple values to a method through a single parameter.
  3. When you want to hold a database record or some values temporarily without creating a separate class.

Tuple Limitations:

  1. Tuple is a reference type and not a value type. It allocates on heap and could result in CPU intensive operations.
  2. Tuple is limited to include 8 elements. You need to use nested tuples if you need to store more elements. However, this may result in ambiguity.
  3. Tuple elements can be accessed using properties with a name pattern Item<elementNumber> which does not make sense.


No comments:

Post a Comment

How to use SQL pagination using LIMIT and OFFSET

  How to extract just a portion of a larger result set from a SQL SELECT. LIMIT n is an alternative syntax to the FETCH FIRST n ROWS ONLY. T...