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);
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)();
1 comments:
I reckon extension methods will never feel as abused as they will with this particular code snippet ;)
Post a Comment