Today I saw Tombatron’s blog post on Iterating Over A Tuple about ways to iterate over a Tuple. While I must say it is a very bad idea to do this (if you want to store your data in something iterable, then use something other than a Tuple), I found a very interesting challenge in this.
Tombatron implements Extension Methods and converts the Tuple into a List which you can iterate from there. The drawback to that method is that Tombatron had to account for every tuple (so Tuple, Tuple, etc) which, while it works, just felt like it could be improved on. So I got to work.
At first I wanted to inherit from the Tuple class but then ran into issues being able to inherit from all of them as there is not one base class. From there I decided that it would be better to start from IEnumerable and go from there. Since this is more or less a proof of concept for myself, I decided to use a List for storage and then just wrap the list’s enumerator with my own.
The next task was figuring out how to support a varying number of arguments. That was achieved by using the params with dynamic to allow for heterogeneous types. On top of that, I created an indexer so that it could still be accessed like the normal Tuple (and without me having to create several functions).
Overall, I had fun creating this little bit of code and know that it will not be used in production (at least I pray it wouldn’t be). Here is the code so you can see what I did: