Tuples for Convenience and Speed
Being a smart programmer means knowing when to use the right tool for the job at hand, and when not to use those same tools! In this post I try to be smart about using the Tuple class, illustrated by an example. Possibly you have already encountered Tuples and were wondering when you should use them; I hope my simple example will provide you with some ideas.
My Problem
I want to use a BackgroundWorker and I need to pass it two arguments (for good reasons which divert from my main point, so won’t be explained here). BackgroundWorker has a method ‘DoWork’, but it only accepts one input arugment!
Here are three alternatives we could use to address the problem:
- We could combine our arguments to a single string, thus creating a single
argument. I prefer not because strings are not strongly typed, and
converting back and forth is work I would like to avoid if possible. - We could make a single-use class, create an instance of it, and pass it
to our DoWork method. Again, more work than I wish to perform. - Or, we could use a Tuple to pack our arguments into a single object, as illustrated in the sample below:
//Pack my variables into a single variable
var args = Tuple.Create(myTotal, myBoolArg);
//Kick-off the worker
_FetchWorker.RunWorkerAsync(args);
...
//Inside the 'DoWork' method, we need to extract
//our arguments from e.Argument
void FetchWorker_DoWork(object sender, DoWorkEventArgs e) {
//Since e.Argument's type is 'object', we need to cast
//it back to the original type
Tuple<int, bool> args = (Tuple<int, bool>)e.Argument;
//Put the arguments into nicely named variables:
int myTotal = args.Item1;
bool myBoolArg = args.Item2;
}
A Couple of Explanatory Notes
Every tuple has properties Item1… Item8, that is, up to 8 items. Every property is strongly-typed, according to this principle: if you put an int in, your tuple gets an int property, if you put a bool in, you get a bool out. The correct property type is created for you, automatically. Whatever type you put in, you get that same type out.
And when I say ‘put it in‘, I mean use the ‘Tuple.Create method’. As many things as you put in (up to 8), that is how many you get out. Simple!
Usage (Abusage?)
Tuples are great for single-use classes. Here is my proposed usage principal: if you use same your tuple in more than two places, then do the work and create a dedicated class instead. Why? Because myClass.Total is more readable than myClass.Item1. ‘Item1’ is generic and requires you to backtrack to understand the purpose, but ‘Total’ is self-explanatory.
This simple sample is just the start, you can use Tuples in many places where you need a quick-and-dirty way to lump data together into a temporary object. Have fun!