I find myself occasionally in C# 3.0 looking for ways to simulate the notion of a tuple. Over time I’ve had various “poor man’s” implementations, here are a few of them:
Basic Object Array:
object[] poorTuple = new object[]{foo,bar,baz}; // basic object array
More Strongly Typed, HoHoHo…
KeyValuePair<TypeA, KeyValuePair<TypeB, TypeC>> poorTuple;
Implementing a class that can use type inference (lifted from Functional Programming for the Real World)
public static class Tuple{
public static Tuple<T1, T2> Create<T1 foo, T2 bar>{
return new Tuple<T1, T2>(foo, bar);
}
}
// later:
var data = Tuple.Create("foo", 42);
Questions:
-
Any other ways to have a poor man’s tuple in C# 3.0 (or language of choice that lacks the data structure).
-
What is the best way to get a tuple in C# 3.0 – if anyone has a library recommendation it is welcome.
-
At what point (yes, generalize for me) does it make sense to create a specific type rather than something like a list or tuple? (looking for rules of thumb)
You can create anonymous types which function similarly to tuples, except with useful names: