4 ms·
One way to do very case specific pattern matching in C# is to write an extension method that takes a lambda for each case. For example, my maybe type for C# has
by Strilanc 12y ago
One way to do very case specific pattern matching in C# is to write an extension method that takes a lambda for each case. For example, my maybe type for C# has `Match`:
may.Match(
() => print("None"),
val => print("Some: " + val))
Not very flexible, or performant, but covers the basics of common cases.
- munificent 12y agoI came up with some similar and wrote a long blog post[1] about it several years ago. I never ended up using it in practice because it felt too syntactically weird, but it was a fun little exercise. [1]: http://journal.stuffwithstuff.com/2009/05/13/ml-style-pattern-matching-in-c/ http://journal.stuffwithstuff.com/2009/05/13/ml-style-patter...
- louthy 12y agoI created a very similar one to you also, and found the same. It's just a bit too clunky syntactically. The only time I'd use it would be if I'm using it as part of an expression where a (switch or series of if) statement would break the expression up. As well as a generic extension on Object I started adding bespoke Match extension methods to a monads library that I've been working on [1] (which again was all about trying to coerce C# into a more expression based style). So the Option monad Match method would work like so: Func<int> res = (from x in DoSomething() from y in DoSomethingElse() select x + y) .Match( Just: v => v * 10, Nothing: 0 ); Or, the Either monad: var result = (from lhs in Two() from rhs in Two() select lhs + rhs) .Match( Right: r => r * 2, Left: l => 0 ); [1] https://github.com/louthy/csharp-monad https://github.com/louthy/csharp-monad