BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

.NET Framework
.NET 4.0+

Using Tuples

The .NET Framework version 4.0 introduced the ability to create tuples using several related, generic Tuple classes. Tuples provide a convenient way in which to link several values or objects, without first creating a class or structure to hold them.

Creating Large Tuples

The Tuple.Create method allows the generation of tuples with a maximum of eight elements. To create tuples that are larger than this you must use the Tuple<> class that holds eight elements. This version of the class is slightly different to the others as the last item is used to hold a second tuple. This means that if you wish to generate an 8-tuple with the constructor, the eighth argument will be a 1-tuple. To create a 9-tuple the eighth argument will be a 2-tuple.

You can see the creation of an 8-tuple and a 9-tuple in the sample code below. Note that the final type parameter and final argument in each case define the element types and values of the linked tuple. Note also that the output of the ToString method correctly shows the tuple using the standard notation.

var tuple8 = new Tuple<int, int, int, int, int, int, int, Tuple<int>>(
    1, 2, 3, 4, 5, 6, 7, new Tuple<int>(8));

var tuple9 = new Tuple<int, int, int, int, int, int, int, Tuple<int, int>>(
    1, 2, 3, 4, 5, 6, 7, new Tuple<int, int>(8, 9));

Console.WriteLine(tuple8);      // Outputs "(1, 2, 3, 4, 5, 6, 7, 8)"
Console.WriteLine(tuple9);      // Outputs "(1, 2, 3, 4, 5, 6, 7, 8, 9)"

NB: If you are creating tuples with a large number of elements you should consider creating a new class or structure to accommodate those values. This will prevent the meaning of the individual elements from being misinterpreted and may improve the readability and maintainability of your source code.

Reading Large Tuple Values

The Tuple class that holds eight elements includes eight properties to provide access to those values. The first seven properties are named Item1 to Item7 and return the first seven values respectively. The eighth property is named, "Rest". This returns the linked tuple that contains the remaining values. You can use the linked tuple's Item properties to gain access to the later elements.

To demonstrate, try executing the following code. This retrieves the first and ninth elements from a 9-tuple. The ninth item is the second element of the linked tuple.

Console.WriteLine(tuple9.Item1);        // Outputs "1"
Console.WriteLine(tuple9.Rest.Item2);   // Outputs "9"
2 November 2010