Introduction to Tuples in .NET Framework 4.0

Introduction

Some data elements usually go in a group. In classical programming languages like C++ programming, you would use structs. However structs were limited to containing value types only. The other choice was to create a tuple for every specific set you would like to create, otherwise you couldn't be assured of data integrity.

Tuple Defined

A tuple is a mathematical concept which is defined as an ordered list of elements. (Source: Wikipedia).

These elements can be of any type so we are not restricted to only a single type as is the case of arrays or generic lists.

Tuples in Managed Code

Tuples came up as a language specific implementation in F# in version 1.0.

In F#, a tuple of 2 numbers can be simply represented as (4, 9) // tuple of two numbers

IronPython also had a tuple type that can be created by specifying elements in the parentheses: (1, 2, 3)

With the growing popularity of the tuple type and its lack of presence in mainstream languages like C# programming and Visual Basic prompted the Common Language Runtime folks to think about adding support for the tuple in the Base Class Libraries. This had two advantages:

  1. There will be no need for language specific implementation for creating a tuple.
  2. With tuple as a Base Class Library type, its behavior can be guaranteed by the CLR team to work without issues that can arise from language specific implementations.

With this in mind, the CLR team created the Tuple class in the System namespace in .NET Framework 4.0. The Tuple is a factory class which provides methods to create instances of itself.

To create a tuple, call Tuple.Create() as below:

  var t = Tuple.Create(1, 2, "Hello Developer");

The Tuple class provides 8 overloads of Create to create tuples of variable length. A tuple with 8 or less members can be created by direct overloads.

  var singleTuple = Tuple.Create(1);
  ...            
  var octuple = Tuple.Create(1, 2, 3, 4, 5, 6, 7, "Eight");

Number of elements in a tuple is somewhat restricted by the number of available overloads of the Tuple.Create method. The CLR team must have researched and found that tuples of more than 8 elements would not be common. And hence they only provided overloads which can take a maximum of 8 elements. To create tuples of more than 8 elements, one can compose a tuple of n-7 elements (where n is the total number of elements) and add that tuple as the 8th element of the desired tuple.

For example

  var tenTuple = Tuple.Create(1, 2, 3, 4, 5, 6, 7, Tuple.Create(8, 9, 10));

Difference Between a Struct and a Tuple

The classical "struct" and the tuple might look remarkably similar. They both are a representation of sets (things that go together). However there are key differences between them:

  • Struct is a value type (since it has elements which are value types. Tuples are reference types
  • Struct lies on the stack (value types) and tuples are on the "managed heap". Struct could go out of scope as soon as the method containing the struct exits. Tuples on the hand other will be garbage collected.

Hands On

Let us create a .NET Framework 4.0 application that shows the usefullness of tuples.

  using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Text;
  
  namespace TupleDemo
  {
      class Program
      {
          static void Main(string[] args)
          {
              var singleTuple = Tuple.Create(1);
              var doubleTuple = Tuple.Create<int, long>(1, 1);
              var tripleTuple = Tuple.Create(1, 1, "Three");
              var quadruple = Tuple.Create(1, 1, "Three");
              var octuple = Tuple.Create(1, 2, 3, 4, 5, 6, 7, "Eight");
              var tenTuple = Tuple.Create(1, 2, 3, 4, 5, 6, 7, Tuple.Create(8, 9, 10));
  
  
              Console.WriteLine(singleTuple.ToString());
              Console.WriteLine(doubleTuple.ToString());
              Console.WriteLine(tripleTuple.ToString());
              Console.WriteLine(tenTuple.ToString());
  
          }
      }
  }

Listing 1 - Program.cs

When we debug the above code using Microsoft Visual Studio 2010, we see that the object tenTuple is shown as a composite tuple consisting to seven integers and the eighth element being a tuple.

The output of the above application is below. It shows that tenTuple is a composite tuple.

  (1)
  (1, 1)
  (1, 1, Three)
  (1, 2, 3, 4, 5, 6, 7, (8, 9, 10))

8 Things You Might Not Know About Tuples

  • Tuples are immutable.
  • Tuples are read-only.
  • Tuples are reference types and hence reside on the managed heap.
  • Tuples do not have constructors. They have static method to instantiate themselves.
  • You cannot create a variable of type Tuple with the command "Tuple t". You create a var.
  • Each element of tuple can be a different type.
  • A very simple type of tuple in the earlier versions of .NET was the System.Collections.Generic.KeyValuePair, though it emphasized a relationship between its two elements.
  • Type safety is assured in Tuples by the .NET framework.

Conclusion

In this article, we saw how to have structured data sets using Tuples, a new feature of .NET Framework 4.0. We have created a sample which is attached to this article which can you use to better understand tuples.

Related Articles



About the Author

Vipul Vipul Patel

Vipul Patel is a Software Engineer currently working at Microsoft Corporation, working in the Office Communications Group and has worked in the .NET team earlier in the Base Class libraries and the Debugging and Profiling team. He can be reached at vipul_d_patel@hotmail.com

Downloads

Comments

  • Tuple is allowed

    Posted by RossPatterson on 11/02/2010 04:41pm

    You can indeed declare Tuple variables with their explicit type, not just with "var".  According to the class doc (http://msdn.microsoft.com/en-us/library/dd268536.aspx):
    
    You can instantiate a Tuple object by calling either the Tuple constructor or the static Tuple.Create(T1, T2) method.

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • A global data storage provider whose business is booming needed a best-in-class data center to serve as the backbone of its technical operations going forward—and it needed it delivered within a year.

  • A help desk is critical to the operations of an IT services business. As a centralized intake location for technical issues, it allows for a responsive and timely solution to get clients and their staff back to business as usual. In addition to handling immediate IT issues, a help desk performs several proactive tasks to ensure clients' IT systems remain operational and downtime is minimized. Thus, utilizing a help desk and following best practices can improve the productivity, efficiency and satisfaction of …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds