It was mentioned in the Book but it didn't really give an explanation on what it does or what it is. Could anyone tell me what it is?
Date: 25 Feb 2013 05:21
Number of posts: 3
RSS: New posts
It's a generic class for storing a collection of a specific number of items.
For instance, there's a double or a couple if you have two things, a triple if you have three, a quadruple for four, a quintuple for five, etc. A "tuple" is just a word for saying some non-specific number like that. (Note that the five one ends with "tuple", as does most of the numbers after that.)
Imagine you have a scenario where you have more than one thing you want to return from a method. As kind of a quick, rough example, let's say you're doing a division problem, and you want to be able to return the quotient and the remainder at the same time. One way to do this would be to return an array with two items in it. Sometimes, this is a great solution. But it has a couple of drawbacks to it. For one, when you get the array back, you technically can't be sure that it has exactly two items in it. It may have 0 or 10. Or it may be null. So you have to write code defensively, and make sure that what you get back actually has two items in it. The second problem is that if you're trying to return two things that have very different types, your array would need to be the object type. That means a lot of casting, which is not so great.
The second option is to use output parameters. (These are also talked about in the book.) This gets around the problems the previous solution had, but it has it's own set of problems. Like the fact that you have to declare the variables where things will get stored in advance, you have to put in the out keyword, etc. None of these things are all that bad, but they're not super awesome either.
So as an alternative, there's the Tuple class. In fact, if you look around, there's lots of tuple classes. One for two items, one for three, one for four…. I don't remember how high up it goes, but it seems like 8 or 18.
So if you want to return your quotient and remainder, you could return them as a tuple:
// Pretend these are passed in. int a = 9; int b = 4; int quotient = a / b; int remainder = a % b; Tuple<int, int> results = new Tuple<int, int>(quotient, remainder);
Off the top of my head, I don't remember how you access these, but it's something like Item1 and Item2, etc., I think.
int quotient = results.Item1;
So it can be pretty convenient and helpful, but here's the thing. If you're going to be using this in lots of places, you should just create a class (or struct, whatever makes the most sense) to dump the data in. This would work in the same way, but you can choose what to name your items. You can call it Quotient and Remainder, instead of Item1 and Item2, which is extremely vague.
Is that the kind of information you were looking for?