OH: “Just Use a Tuple” – Say What?

March 29, 2011

ASP.NET, C#, Learning, Tuple

After hearing someone at a conference  tell a presenter, “just use a tuple to solve that,” then seeing tuples all over the place when I was stepping through the Sprite and Image Optimization Preview 3 on Codeplex, I wanted to see what this new buzzword was all about.

My initial web searches led to these Tweets:

TwitterTuple1TwitterTuple2

The concept of Tuples being an IMMUTABLE instance of a class was intriguing to me & led to me running some curiosity tests.

If a Tuple is immutable, what happens when it’s created with a reference type?

ChangingTupleReferenceTypeProperty

So that was interesting (albeit not surprising)… the Tuple properties themselves are indeed immutable (read-only), as are the value types since they don’t have pointers. The reference types are modifiable (was able to access pointers both through my initial var & through the Tuple Item1 Property pointer).

What Else? Should I Even Care? Why?

Upon further reading, the “basics” of c# Tuples became pretty fascinating. Here are a few things I found particularly noteworthy:

From http://msdn.microsoft.com/en-us/library/system.tuple.aspx:

Tuple is a factory class that provides static methods for creating instances of the tuple types supported by the .NET Framework. It provides helper methods that can be called to instantiate particular tuple objects without requiring that you explicitly specify the type of each tuple component.

Helper methods directly support the creation of tuple objects that have from one to eight components (that is, singletons through octuples). Although there is no practical limit to the number of components a tuple may have, helper methods are not available to create a tuple with nine or more components. To create such a tuple, you must call the constructor.

”Tuple is a factory class” – I have to admit, that definition piqued my interest, as this is the first time I’ve personally seen something defined as such on msdn, referring to a built-in .NET Framework feature.

The fact that tuples can be created either by a constructor or via Tuple.Create (up to octuples) driven by Helper methods is some kind of Intellisense magic right there, crazy-cool.

Tuples did not exist in .NET Frameworks < 4.0.

I continued to search, trying to figure out if I care (and why these were added), and came across this link that says, “This can be handy for returning more than one value from a method (without using out or ref parameters)”

[record scratch] Wait a minute… srsly?!? How many times have I written methods that I need to return multiple non-reference types from that aren’t worth creating a class for, so I’ve create bool or int out params? Ok honestly the answer is probably fewer than ten, BUT enough to see the power of this new Tuple type imo.

#AmIMissingSomething – Yes, I Was!

For grins, let’s use the out param example in the msdn documentation (but feel compelled to ask – do people really combine “void” return with out params or was this just done in the example so as not to confuse?):

class OutReturnExample
{
static void Method(out int i, out string s1, out string s2)
{
i = 44;
s1 = "I've been returned";
s2 = null;
}
static void Main()
{
int value;
string str1, str2;
Method(out value, out str1, out str2);
// value is now 44
// str1 is now "I've been returned"
// str2 is (still) null;
}
}

I’ve personally found it a bit of a pain (not to mention it feels sloppy) to have to Instantiate (“new up”) the variables every time I want to call a method with out params, but tuples can change that code to this:

class OutReturnExample
{
static Tuple Method()
{
string s2 = null;
return Tuple.Create(44, "I've been returned", s2);
}
static void Main(string[] args)
{
var outParamTupleReplacement = Method();
// outParamTupleReplacement.Item1 is 44
// outParamTupleReplacement.Item2 is "I've been returned"
// outParamTupleReplacement.Item3 is null;
}
}

OldAndBustedOutParamToSexyTuple

Ooh – code is more elegant while not losing readability… I find that to be pretty darn cool.

Please note: Yes, leaving that method named, “Method” was not something I feel good about but done for comparison to out param example only.

I realize this post didn’t take a journey through F# like it seemed like it might, but who knows? Maybe by scratching the surface, finding a place in my current toolbelt for this new type, it will lead to further exploration & understanding of F#, as well as other programming concepts I might, one day, wonder how I lived without.

5 Comments on “OH: “Just Use a Tuple” – Say What?”

  1. Jeff Certain Says:

    Thanks, Cori. I have to admit I was aware of tuples, but didn’t really grok them. Your explanation of them has me itching to go in and refactor code, since I can immediately think of several places these will come in handy.

    Having said that, it feels like much of the value of tuples is that they allow you to avoid creating a class or structure to return the collection of return types. I’m not convinced this will always be a good things — it feels like there’s a danger of losing clarity. Given that the tuple type is part of the framework, and won’t cause reference chain issues when passing them between projects, the slight degree of vagueness might end up being worth it.

    As you said, one more tool in the toolbox. Thanks again!

    Reply

  2. adam Says:

    If you need an N-uple you probably need and object so *go and create one*. The next maintenance developer (it may be you) will not thank you for your tuple-tastic approach.

    Tuples should have been called RandomDataBag.

    Or maybe it’s just me

    Reply

  3. LR Says:

    Tuple is my next pet’s name, ha ha…it will be neutered. I recently learned the most basic definition of tuple at a Standford online course. As a (mainly) HW engineer, I know I am way behind in the latest in everything. I highly recommend taking some of the free online courses that Standford (and others) teach online for course credit that anyone can join in on (and take the quizzes, etc.) on Coursera.org I look at this and wonder what I could have done had I had access to this as a bored teenager (we didn’t have TV, and church was my only social outlet until college.)

    Reply

  4. radarbob Says:

    ” How many times have I written methods that I need to return multiple non-reference types from that aren’t worth creating a class for, so I’ve create bool or int out params?” BAM! That woke me up. Until just then ‘tuple’ a technical term in E/F Codd’s book that I could not understand why it’s used as a generic, formless, pointless, blob in .NET

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: