I think it s good to create a new type when it makes sense to introduce a new value set into your program. For example, if you are writing a complex calculator, then make a complex number type. If you really just want to "glue" a few variables together for a moment, then a tuple is probably a better choice. Let s say you ve got a simple function that gathers two numbers from the console... you might do something like:
static void GetNumbers(out int x, out int y) { ... }
...
int x, y;
GetNumbers(out x, out y);
I think it usually makes sense when a "getter" function has a return value but in this case it doesn t because I can t really have two return values. I could go and make a new type called TwoNumbers and use that but I think this quickly becomes more of a problem than a solution. If C# had tuples I may be able to do something like the following:
static (int, int) GetNumbers() { ... }
...
int x, y;
(x, y) = GetNumbers();
Now the really interesting question is: although C# doesn t have this feature am I able to implement it myself with a library? The code you suggest is a start but won t allow me to assign like I ve done in the second example. I m not sure about C# but you can get really darn close to this in C++ by using the fact that a function call can be the left operand to the assignment operator when it s return value is a reference type. Consider the following:
// this class is implemented much like yours only with C++
template<typename T1, typename T2> class tuple { ... }
...
template<typename T1, typename T2> tuple<T1, T2>& tie(T1 a, T2 b) { ... }
...
template<typename T1, typename T2> tuple<T1, T2> get_numbers() { ... }
...
int x, y;
tie(x, y) = get_numbers();
I d say that is pretty darn close... instead of (x, y) =
we have tie(x, y) =
. If you are interested in implementation details, I ll refer you to the TR1 library where I first learned about this:
http://www.boost.org/doc/libs/1_41_0/libs/tuple/doc/tuple_users_guide.html#tiers
So to bring all this back to C# 3.0... we can certainly create a generic tuple class as you ve shown, but can we create a function like tie to "unpack" the tuple in C#? I haven t tried it, sounds like fun. Without something like that, I d be reluctant to let a C# tuple library proliferate through my code.