Pattern matching in C# – part 4 – more tuples

DISCLAIMER: this post has been written months ago and never posted. By that time I was still trying to bring F# goodness to C#. This might be easier today with Roslyn, but that is not the path I’ve taken. Since the last post of this series, I’ve been doing more and more F#, even during my day job. I don’t think I’ll ever post this kind of ‘’How to do F# in C#” posts. What you can expect from this blog is now mostly functional programming in F#…

Today’s post will be a short one, as an answer to question from several months ago:

But if we want to handle tuples with more values… do we have to write all the overloads ?!

The answer is yes. With the current implementation, there has to be a method overload for every combination of patterns that you want to be able to match…

But wait a minute… For a given tuple of n values, there are 3n combinations… That makes a lot of methods to write ?!

You don’t have to actually write all these overloads yourself! T4 templates are there exactly for that purpose. If we want to generate all the extensions methods for the tuples of 2 elements up to 4 elements, for instance, we just have to build a .tt file, and define the 3 individual patterns as a string array :

And we decompose the caseNumber into an array of int whose values can either be 0, 1 or 2, corresponding to the index of the pattern associated with each argument. For instance, with a cardinality of 4 and a caseNumber or 4, we would get an array containing [0, 0, 1, 1] :