Language Features I Wish C# Had – Tuples

Several languages, such as Python, have the concept of a Tuple built into the lanugage. One of things it’s used for in Python is multiple return values. So you can call “return x,y” to return two values. Of course, C# can only return one. If you need to return more values, you have to define out parameters.

LINQ / C# 3.0 / VB 9 support the idea of anonymous types, which is similar to a tuple. The big difference is that, because they’re anonymous, they can’t leave the scope they’re defined in. In other words, they’re great within a function, but if you want to pass them out of your function type-safely, you have to define a non-anonymous type for them.

Interestingly enough, F# supports tuples, though it a bit of a hack. Since the CLR doesn’t support tuples, F# basically defines different Tuple classes for up to seven tuple parameters (i.e. Tuple<t1,t2,t3,t4,t5,t6,t7>), For .NET 1.x, it’s even worse – they have to define different type names (Tuple2, Tuple3, etc). Ugh.

Update: Robert Pickering pointed out that F#’s tuple implementation is entirely transparent inside of F#. He’s right – I was writing from the perspective of a C# developer using F#’s implementation of tuples. Maybe I need to be looking closer at F#?

Comments:

Harry, How does a Truples diffe from an 'object' in .NET core. Could I not return an object from a routine, and define the structure dynamically? What about a collection? It seem that Truples appear to be nothing more then a UDT model, and that already is there. I may be missing something, so if I am off base, just let me know :) Tom
I don’t the implementation of tuples in F# is a hack; you are simply talking about the implementation details. If you are passing the tuple between two functions in F# then it is totally transparent you do not see the implantation details you describe. Sure if you pass a tuple between F# and C# then you are forced to deal with the Tuple classes that F# provides, and this is a little ugly, but I can see another way this could be supported in languages that don’t support tuples.
Tom, Tuples are different to what you describe. A tuple is just a way of returning two values from a method with out having to define a type to contain them. For instance in F# you can say: let my_tuple = 1, 2 To create a tuple, then to retrive a value from a tuple you would say: let _, x = my_tuple And then x would hold the value 2. Wikipedia has a good definition: http://en.wikipedia.org/wiki/Tuple Cheers, Rob
Robert, you're right. I think it feels like a hack if you use F# tuples outside of F#, which was the context of my post in the first place.