Tuesday, 3 June 2008

Try-catching in a single line of code

Do you like reducing your line count at the expense of readability to others? Then you'll like this!

public static class FuncExtensions { public static TResult Catch<TExc, TResult>(this Func<TResult> func, Func<TExc, TResult> handleException) where TExc : Exception { try { return func(); } catch (TExc ex) { return handleException(ex); } } }

This lets you write things like:

int x = new Func<int>(DoSomething).Catch((NullReferenceException e) => -1);
instead of
int y; try { y = DoSomething(); } catch (NullReferenceException ex) { y = -1; }


You can of course write overloads for Funcs that take more than one parameter.

Edit: I've written a version that lets you chain catches but I'm not sure if its better or not...

int x = new Func<int>(DoSomething) .Catch((NullReferenceException e) => -1) .Catch((NotImplementedException ex) => -2)();

Monday, 2 June 2008

storing ViewState in memcached - the ultimate post

The HttpModule for storing memcached in the ViewState is dead - I discovered that you can far more easily intercept ViewState using a custom PageAdapter. Please go to http://code.google.com/p/memcached-viewstate/ for frictionless memcached viewstate goodness! Hopefully this is the end of the matter :)