Skip to main content

Tuples in C# 7.0

What is a Tuple?

              A Tuple is a finite ordered list of values, of possibly different types, which is used to bundle related values together without having to create a specific type to hold them or else we can say Tuple is a temporary grouping of values.

             so, a tuple is basically a data-structure. A tuple has a specific number and order/sequence of elements. 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.

            We may often write methods which return multiple values so we need to create a simple structure containing more than one data elements. To support these scenarios, tuples were added to C#. Tuples are lightweight data structures that contain multiple fields to represent the data members.
Here you can find how tuple can be used, Look at the following example:

(string, string, string) GetEmployee(int id) {
    //Retrieve data from database
 return (address,age,designation);

The method above returns three strings.
 var emp =  GetEmployee(int id) ;  //here is the caller function    
 WriteLine($"Employee: {emp.Item1} {emp.Item2} {emp.Item3}.");

Instead of using default names Item1, Item2 etc.we can use property itself, For that we can define property names in return values as shown in the following example:
(string address, string age, string designation) GetEmployee(int id)
var emp = GetEmployee(id);
WriteLine($"Employee {emp.address} {emp.designation}.");e caller function    
WriteLine($"Employee: {emp.Item1} {emp.Item2} {emp.Item3}.");

we can also specify element names directly in tuple literals:
return (address: address, age: age ,designation: designation);

So that was all about tuples and since every coin has two sides let's see the advantages and disadvantages of tuples.

Advantages and when to use a tuple

  •  Returning multiple values from the function/method.
  •  Composite Key in a dictionary.
  •  Easy access and manipulation of a dataset.
  •  Replacement of a class whose sole purpose is to carry around data and bind a combo box or other control.
  •  Pass multiple values to the function/method.

Disadvantages and When to avoid.

  • Tuples are classes, not structs so it would be allocated on the heap rather than the stack so its kind of overhead on the garbage collector.
  • Tuples are not so syntactically mature so the code is less readable, so use it for internal classes but avoid exposing them to external classes.
  • You can't document the passed in parameters.
  • Sometimes key-value pairs are not just sufficient for our requirements, go ahead and try tuples in those scenarios.