Introduction of ‘Tuple’ in .NET Framework 4.0, really filled in a missing piece in C#. Apart from giving us the ability to interoperate with functional languages like F# or Python/Ruby, It does offer the convenience of heterogeneous collection which can take form of any class or structure that you would have created otherwise.
In C#, I feel Tuple syntax is still in its early stages and I am hopeful it will take more friendly syntax in next iterations. I have been explaining the concept of Tuple quite a while now during my presentations. Some of the questions that people ask me during my presentations are:
My answer to these questions are as below:
The other scenario where you can use this is to avoid anonymous types.
Thanks Arun for pointing this. You post is really nice. You're correct - Avoiding Anonymous Types is another usage for Tuples.
Personally I don't like Tuples for day-to-day programming. For interoperability that's fine, but one of C#'s best design principles (and, I suspect the reason it took so long to wedge Tuples into the feature set) is it's type-safe and descriptive approach to objects. With Tuples, on the other hand, you can basically make a "random bag" which contains random objects. When I write my code to receive a Tuple<string, string, int> what does that mean? Unless someone tells me the only way to figure it out is to trace through the code that sent it to me. Yuck!
I'm with Mike. I feel dirty every time I use Tuple. Item1, 2, and 3. What ARE they?
I am also not a big fan of the syntax and the pattern matching which is in-built with Tuple in C# at this point. However - as I said in this post, it is still very nascent. I am hopeful it will change as the concept evolves further.
I have found a use for Tuples to eliminate methods that have too many parameters. For example, when you build a class that queries the database based on several search parameters, instead of having a method that takes 5 parameters, have it take a tuple that holds those values so you still only pass in one object. Helps make the code readable as long as you use metadata to help make the purpose clear.