Assertfail

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:

TypeMatch.Case(exception,
  (GnarlyType e) => { HandleGnarly(e); },
  (FuncyType e1) => { HandleFunky(e1); },
  () => { Explode(); });

Instead of:

var e = exception as GnarlyType;
if (e!=null){ HandleGnarly(e); }
else {
  var e1 = exception as FunkyType;
  if (e1!=null){
    HandleFunky(e1);
  }else{
    Explode();
  }
}

Small note

This type of feature is now part of C# proper as:

switch (exception)
{
  case GnarlyType e: HandleGnarly(e); break;
  case FunkyType e1: HandleFunky(e1); break;
  default: Explode(); break;
}

Tags


Comments

Do you want to send a comment or give me a hint about any issues with a blog post: Open up an issue on GitHub.

Do you want to fix an error or add a comment published on the blog? You can do a fork of this post and do a pull request on github.