Pattern matching in C# – part 3 – tuples

Hello again, you potential RSS subscriber (probably still reading this in Google Reader, trying to determine which reader you’ll choose next) ! Last time I left you with a working pattern-matching mechanism in C#, but very limited… as it could only match a single value at a time.

What makes the pattern-matching mechanism so powerful in functional languages is its ability to match many sorts of data structures, amongst which are tuples.

Defining a match expression on a tuple or 2 values in F# can be done this way :

This trick allows me to define methods with a MatchCase-typed parameter to handle the wildcard pattern case. Moreover, if I add the following line before my patterns definitions :

var _ = MatchCase.Any;

I’m then able to use a simple “_” to represent the “any” case.

The method used previously to build the pattern matching Func and its invocation in the Eval method doesn’t change: only the “recording” process is impacted. The pain point here is that we need to define each necessary overload of the Case extension method, in order to handle all the patterns. These extensions methods are all based on the following model:

The implementation of each method follows the same pattern as in the previous post, and builds an expression that determines whether a given tuple matches the pattern, returning, and evaluates the selector expression when there is a match.

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