Will a future version of .NET support tuples in C#?

Graviton picture Graviton · Sep 30, 2008 · Viewed 33.2k times · Source

.Net 3.5 doesn't support tuples. Too bad, But not sure whether the future version of .net will support tuples or not?

Answer

Andreas Grech picture Andreas Grech · Jun 26, 2009

I've just read this article from the MSDN Magazine: Building Tuple

Here are excerpts:

The upcoming 4.0 release of Microsoft .NET Framework introduces a new type called System.Tuple. System.Tuple is a fixed-size collection of heterogeneously typed data.    

 

Like an array, a tuple has a fixed size that can't be changed once it has been created. Unlike an array, each element in a tuple may be a different type, and a tuple is able to guarantee strong typing for each element.

 

There is already one example of a tuple floating around the Microsoft .NET Framework, in the System.Collections.Generic namespace: KeyValuePair. While KeyValuePair can be thought of as the same as Tuple, since they are both types that hold two things, KeyValuePair feels different from Tuple because it evokes a relationship between the two values it stores (and with good reason, as it supports the Dictionary class).

Furthermore, tuples can be arbitrarily sized, whereas KeyValuePair holds only two things: a key and a value.


While some languages like F# have special syntax for tuples, you can use the new common tuple type from any language. Revisiting the first example, we can see that while useful, tuples can be overly verbose in languages without syntax for a tuple:

class Program {
    static void Main(string[] args) {
        Tuple<string, int> t = new Tuple<string, int>("Hello", 4);
        PrintStringAndInt(t.Item1, t.Item2);
    }
    static void PrintStringAndInt(string s, int i) {
        Console.WriteLine("{0} {1}", s, i);
    }
}

Using the var keyword from C# 3.0, we can remove the type signature on the tuple variable, which allows for somewhat more readable code.

var t = new Tuple<string, int>("Hello", 4);

We've also added some factory methods to a static Tuple class which makes it easier to build tuples in a language that supports type inference, like C#.

var t = Tuple.Create("Hello", 4);