All Posts assertfail

View the Blog on GitHub wallymathieu

Type matching in c#

22 Nov 2012

I was thinking about how nice you have it in some languages where you can do a case statement for types. Thing is, we have a lot of compiler goodness in C# already.

By being explicit about the type and using type inference we can have a generic Case statement of a maximum length (depends on how many if else you think are ok to add).

I find it pretty sweet to write code like this:

<blockquote class="tr_bq"> TypeMatch.Case(exception,
  (GnarlyType e) => { HandleGnarly(e); },
  (FuncyType e1) => { HandleFunky(e1); },
  () => { Explode(); });</blockquote>
Instead of:
<blockquote class="tr_bq"> var e = exception as GnarlyType;
if (e!=null){ HandleGnarly(e); }
else {
  var e1 = exception as FunkyType;
  if (e1!=null){


  • c#
  • Comments or errors? Fork post and do a pull request on github