/ .net

The Tuples Are Coming

Great to see the tuple types, that some of you might have stumbled upon in F#, is being included in the BCL upcoming .NET 4.0 release. Tuples are strongly typed sequences that unlike strongly typed arrays can have items of different types. For example a tuple can contain (1,2,"many"), and can e.g. be compared to the tuple (1,2,"many"), of course resulting in true. Or should it? The BCL classes are still subject to some polemic on whether tuples are basic values like Point or KeyValuePair, or reference types like arrays. There are surprisingly many choices to be taken concerning a seemingly simple type like this, that dramatically defines its usage and number of potential bugs in written code. In the current state of the BCL, the above example results in false because the Equals(x) or == methods treats the tuples as reference types, ignoring the individual field values! Instead IStructuralEquatable interface is added that should be used if the field values are to be compared. If you forget this special case, no compiler or runtime errors will occur, but the app will not work as expected. Aw snap! After taking a glance at Wikipedia's definition it is obvious that the CLR has some shortcomings that make it hard or very tedious to implement. For example supporting the (1, (2,3.0)) == ((1,2), 3.0) would result in writing an exponential number of factory methods. I implemented a .NET 3.0 compilable version somewhat like the upcoming BCL4.0 version. Note I did not implement the IStructural* interfaces: My Equals compares each field value, so use object.ReferenceEquals if you want to compare the addresses. The source code is on http://tuples.codeplex.com/ and you can download the assembly directly from here.