Via Don Box’s blog, I found the preliminary code for a tuple at CodePlex. The tuple is a simple structure containing in this case two values: a double tuple. It basically looks like this :
Structure Tuple(Of TFirst, TSecond)
Public Property First() As TFirst
Public Property Second() As TSecond
End Structure
I’ve omitted the details, such as the constructor or equality overloads and operators etc.
So Tuple’s can be handy general purpose storage to pass around a couple of values. Let’s say I write a Parse method such as :
Function Parse(ByVal value As String) As Tuple(Of Int32, Boolean)
Dim iVal As Int32
Dim success = Int32.TryParse(value, iVal)
Return New Tuple(Of Int32, Boolean)(iVal, success)
End Function
That makes it a little easier for calling code to parse a string to an int32, but the problem they then face is the values are First and Second. For example:
Dim tuple = Parse("1")
Dim i? = If(tuple.Second, tuple.First, Nothing)
Wouldn’t it be nicer if that could be written as :
Dim tuple = Parse("1")
Dim i? = If(tuple.Success, tuple.Value, Nothing)
Sure you could write your own structure for this, but then we are back to type bloat. That level of detail, Success and Value are only needed at design time, so they could be compiler magic based on XML comments. Perhaps something like this on my Parse method would make the tuple parameters appear as Success and Value instead of First and Second :
''' <summary>
''' A Parse wrapper for string to integer
''' </summary>
''' <param name="value">a string representation of an integer value</param>
''' <returns>
''' <tuple>
''' <First name="Value">the integer value or 0 if the parse fails</First>
''' <Second name="Success">true if the parse succeeds, otherwise false</Second>
''' </tuple>
''' </returns>
Function Parse(ByVal value As String) As Tuple(Of Int32, Boolean)
Dim iVal As Int32
Dim success = Int32.TryParse(value, iVal)
Return New Tuple(Of Int32, Boolean)(iVal, success)
End Function
The down side of this is it would only work with the immediate assignment, and one could argue only when it is used with type inference (as I did above). I doubt the cost justifies the benefit, but imagine the fun you could have if it was a cooking tuple: you could have a double Tuple with Boil and Bubble
(I can’t believe I left that last line in here ;) )