Is there any benefit to this switch / pattern matching idea?

After trying to do such “functional” things in C# (and even attempting a book on it), I’ve come to the conclusion that no, with a few exceptions, such things don’t help too much.

The main reason is that languages such as F# get a lot of their power from truly supporting these features. Not “you can do it”, but “it’s simple, it’s clear, it’s expected”.

For instance, in pattern matching, you get the compiler telling you if there’s an incomplete match or when another match will never be hit. This is less useful with open ended types, but when matching a discriminated union or tuples, it’s very nifty. In F#, you expect people to pattern match, and it instantly makes sense.

The “problem” is that once you start using some functional concepts, it’s natural to want to continue. However, leveraging tuples, functions, partial method application and currying, pattern matching, nested functions, generics, monad support, etc. in C# gets very ugly, very quickly. It’s fun, and some very smart people have done some very cool things in C#, but actually using it feels heavy.

What I have ended up using often (across-projects) in C#:

  • Sequence functions, via extension methods for IEnumerable. Things like ForEach or Process (“Apply”? — do an action on a sequence item as it’s enumerated) fit in because C# syntax supports it well.
  • Abstracting common statement patterns. Complicated try/catch/finally blocks or other involved (often heavily generic) code blocks. Extending LINQ-to-SQL fits in here too.
  • Tuples, to some extent.

** But do note: The lack of automatic generalization and type inference really hinder the use of even these features. **

All this said, as someone else mentioned, on a small team, for a specific purpose, yes, perhaps they can help if you’re stuck with C#. But in my experience, they usually felt like more hassle than they were worth – YMMV.

Some other links:

Leave a Comment