Hit enter after type your search item

The C# Tuple class

A tuple, introduced in .Net version 4.1, can be defined as a data structure having a specific number and sequence of elements. For example, a tuple with two elements:

Tuple <int, string > tup_demo = new Tuple<int, string >(101, “Mike”);

In the above line of code, a tuple is created with two different data type items. The tuple is supposed to store the ID and Name.

The tuple supports up to seven elements directly. That is:

Tuple<Type1, Type2, Type3, Type4, Type5, Type6, Type7,TRest>

If you want eight or more then you use the nested tuple objects in the Rest property of tuple (see the last example).

The following section that details how to create a tuple, access its items and other aspects with examples.

An example of creating a tuple in C#

This example shows how to create a C# tuple with four items. I used int, string, decimal, and string types for the items for storing ID, name, salary and joining date of the employee.

Have a look at creating, assigning values and then accessing the tuple items:

The result:

c sharp tuple

You can see the tuple items are accessed by Item1, Item2 and so on properties. You may use up to seven elements while the eighth element is the Rest property.

Did you know? In C# 7.0, the ValueTuple structure is introduced. You may download the System.Valuetuple 4.3.0 NuGet package if you don’t see the ValueTuple available in your project.

Creating a tuple without specifying the type

A tuple can also be created without specifying the type of items. For that, you may use the helper class Tuple.  The example below shows how to create the same tuple as in above example without the item types:

The output should be the same as in above example except for the difference in item values.

Using tuple in Dictionary example

You may also use a tuple with Collections like List, Dictionary etc. In the following example, we have created a Dictionary object and used a tuple for creating a telephone directory (for the sake of demo only).

The output:

c sharp tuple dictionary

The directory shows serial no, name, address and telephone number as the output as we iterate through the tuple.

In real applications, the source of tuple values can be database driven and each record can be added by using the add method of Dictionary or List<T>.

As mentioned earlier, a tuple may contain only seven items; if you need more you may use the nested tuple as eighth item.

Creating a nested tuple example

The following example shows how to create a nested tuple.

The result:




You can see, we created seven items of int and string type. For the eighth item, Tuple.Create is used to create another tuple (nested tuple).

For accessing the nested tuple first item value, we used Rest property i.e.




This div height required for enabling the sticky sidebar