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)();

Submit this story to DotNetKicks

1 comments:

Rex said...

I reckon extension methods will never feel as abused as they will with this particular code snippet ;)