Tuples in .net considered...

27 May 2012

One of the features that became available in .Net 4.0 was a built in type for a Tuple. Tuples are useful within the scope of a function, where having an ad hoc data structure that holds a set of related values together can make writing an algorithm a little easier. The best part of a feature like this is that you can focus on what your algorithm should be doing, and a little less on the class definitions required to support the algorithm.

The first sign of trouble is when you use a Tuple as a return type. If you’ve spent 5 minutes with them in C#, you will notice how ugly that can get. All of the sudden, you’re trying to figure out what the String value stored in Item1 is, and what the String value store in Item2 is. As projects grow, this can quickly make it impossible for other developers to discover what the reference they’re working with actually represents

Aside from the main drawback, that you have no idea what the return value from a method is trying to represent, C# 2.0 included a much more intuitive/informative syntax for defining single-use types in algorithms: Anonymous Types. There’s virtually no reason to use a Tuple over an anonymous type within the scope of a method body.

Compare:

    Tuple.Create("bob", marley", 42, true);

With:

    new {FirstName = bob", LastName = “marley", Age = 36 , IsMusician = true};

I’ll grant you that the second takes a bit more typing, but we’re not trying to “Save The Characters.” We’re trying to write an algorithm that we can read and debug. If you later decide to promote the anonymous type so that you can return it from a method, it’s as simple as defining a class with the appropriate properties and changing the new declaration to:

    new Person {FirstName = bob", LastName = “marley", Age = 36 , IsMusician = true};

I’ll bet tools like ReSharper even provide this sort of refactoring. I believe that Tuples were added to support better interop between F# programs and C#/VB.Net applications interesting read on the design of Tuples.

If you’re doing C#-only development, Tuples come at a high cost to code clarity. For the reasons above, I (now) mostly avoid using them (in C#). When I understand how tuples are used in F# a little better, I may change my mind.