Using tuples in C# functions and dictionaries
Have you ever?:
- used KeyValuePair{TKey,TValue} just to hold a pair of values together
- missed the fact that .NET anonymous types can be passed out of the method
- used multiple out references to pass parameters out of the function
- wished that Microsoft has declared Triplet somewhere in the System.
The answer to these problems is a tuple. It is an ordered list of items of some specific length. KeyValuePair, for example, is n-tuple of length 2.
Simply put, tuple is just a piece of data that holds a couple of objects together and does not have any other special meaning or usage.
Tuple classes are normally named like:
- 2 arguments - Pair
- 3 items - Triple
- 4 items - Quad or Quadruple
Sample implementation for these classes (with the proper DebuggerDisplay, ToString(), hashcode and equality routines) could be found in the Lokad Shared codebase).
Variable Composition
Sample usage is trivial. Although, it is more clumsy, than in F#, but that's still convenient in some cases, when writing a new class just for one usage is not feasible:
Tuple<bool,DataTable> SomeTupleFunction()
{
bool thereAreMoreRecords = false;
DataTable table;
// ...
return Tuple.From(thereAreMoreRecords, table);
}
// ...
var t = SomeTupleFunction();
var moreRecords = t.Item1;
var table = t.Item2;
Btw, I've recently seen such over-usage of KeyValuePair:
KeyValuePair<string,KeyValuePair<int,KeyValuePair<...
Representing Keys
Another important feature of tuples is their ability to represent keys in dictionaries and hashsets
Consider the following example:
var set = new HashSet<Triple<int, bool, bool>>
{
Tuple.From(1, true, false),
Tuple.From(1, true, true)
};
Assert.IsTrue(set.Contains(Tuple.From(1,true,false)));
Assert.IsFalse(set.Contains(Tuple.From(2, true, true)));
As you can see, generic tuple implementation, saves us the effort to create our own classes with GetHashCode and Equals overrides.
Please, check out the library for yourself and tell me what you think about this implementation of tuples. How could it be improved?
Tuesday, September 30, 2008 at 20:11
Reader Comments (6)
Shouldn't Tuple naming be:
2 => Tu
3 => Tup
4 => Tupl
?
Bill,
I've never heard of such naming of tuples. But it does definitely violate the guideline of avoiding abbreviations (except the well-known ones) in names of classes and variables.
A poor attempt at humor on my part :)
I too would like to see some Tuple definitions in .Net 4.0
Well, most likely that would be something from FSharp.Core.dll but with the syntax support from the compiler.
I'd prefer C# compiler to have extensible architecture, just like in Boo. Then we would not need to wait for the MS teams to implement something))
Why do you have "Pair, Triple, Quad, Tuple" and not "Pair, Triple, Quad, Quint"?
It is slightly easier for new developers to understand code with tuples this way.