In an earlier post, Tuples in C# 4, a developer asked about tuples with 8 or more items and the idea of nested tuples.
The .NET Framework 4 only supports tuples with up to 8 items and the last item is expected to be a nested Tuple and is represented by the Rest property. Per the documentation:
“The Rest property returns a nested Tuple object that allows access to the eighth though nth components of the tuple.”
Here is a quick example of creating a Tuple and Nested Tuple with a total of 12 items and accessing items 8 through 12 via the Tuple.Rest Property. To Keep things simple we will just deal with integers.
var nestedTuple = new Tuple<int,int,int,int,int>(8,9,10,11,12); var myTuple = new Tuple<int,int,int,int,int,int,int,Tuple<int,int,int,int,int>> (1, 2, 3, 4, 5, 6, 7, nestedTuple); var seven = myTuple.Item7; // 7 var eight = myTuple.Rest.Item1; // 8 var nine = myTuple.Rest.Item2; // 9 var ten = myTuple.Rest.Item3; // 10 var eleven = myTuple.Rest.Item4; // 11 var twelve = myTuple.Rest.Item5; // 12
Notice how the nested Tuple is represented by the Tuple.Rest Property and you access its items using the familiar Item1, Item2, etc. properties. I wish there was a more elegant way to pull this off, but I don’t know of one. And, as far as I know, there is no way to name the properties on a Tuple other than Item1, Item2, etc.
It would have been really nice if the C# team would have made working with Tuples a bit more elegant.
Hope this helps.

Comments