views:

107

answers:

4

I have read about the Tuples provided with the coming-out of the new .NET Framework features, and still am I wondering about how it could be useful in real-world enterprise applications.

Can one give me a brief explanation along with a simple but real-world code sample?

Thanks! =)

+4  A: 

A tuple is just a simple way to return multiple values from a function.

Robert Harvey
Don't think this was the main purpose for creating them
Kamarey
@Kamarey: What is the main purpose for creating them? @Thorarin says it is more likely to be used while coding F# than C#. It also seems to be close to the anonymous types, to my understanding.
Will Marcouiller
@Will Marcouiller: I agree with Thorarin, so he got my +1.
Kamarey
+4  A: 

The best would be easy multiple value returning, so coding performance would be an answer. It's also quite readable.

I.e:

return new Tuple<int, string, char>(1, "some string", 10.00);

Versus something like

public class ReturnMany
{
   public int intValue { get; set; }
   public string strValue { get; set; }
   public decimal decValue { get; set; }
}

return new ReturnMany() { intValue = 1, strValue = "some string", decValue = 10.00 }
Kyle Rozendo
+3  A: 

Tuples in .NET are immutable so they're also an easy way to pass a bunch of values around threads. I'm currently using tuples with Retlang and they're great for use with this type of library.

Julien Lebosquain
Immutability could indeed be an advantage. Anonymous types can't be immutable, so the only other option would be handcrafting a class or struct.
Thorarin
+3  A: 

Tuples aren't currently all that large a benefit in C#, because there isn't any neat syntax for them. However, the concept is very common in functional languages such as F# (new to .NET 4.0).

So, if you're writing part of your application in F# or if you're using libraries written in F#, you might run into them. If you're using only C#, I'd say you're better off using anonymous types. They allow you to name the various properties, whereas they will be called Item1 through ItemX using tuples. Not very descriptive.

Of course, if you want to return multiple values (with different types) from a method, using anonymous types isn't an option, in which case using tuples might be a decent solution if you're making something quick and dirty.

Thorarin
Shame that there's no sugar for them in C#, because yeah, they are really useful to have sometimes.
Chris Charabaruk