Returning a default value in case of errors
Ever wrote something like this?
I hate it. Given that I'm processing some XML files whose schemas I cannot change, there's not much to be done but bite the bullet.
This page gave me the idea for the following helper functions:
Now I can write this:
As an aside, it's really annoying not being able to write something like this:
instead of writing say 5 overloads for Func<T> to Func<T1, T2, T3, T4, T>.
- if (a != null && a.b != null && a.b.c != null)
- result = a.b.c.d;
- else
- result = null;
I hate it. Given that I'm processing some XML files whose schemas I cannot change, there's not much to be done but bite the bullet.
This page gave me the idea for the following helper functions:
- public static T Eval<T, ExceptionClass>(Func<T> func, Func<ExceptionClass, T> onError)
- where ExceptionClass: Exception
- {
- try
- {
- return func();
- }
- catch (ExceptionClass e)
- {
- return onError(e);
- }
- }
- public static T Eval<T>(Func<T> func, Func<Exception, T> onError)
- {
- return Eval<T, Exception>(func, onError);
- }
- public static T Eval<T>(Func<T> func, T defaultValue)
- {
- return Eval<T, Exception>(func, e => defaultValue);
- }
Now I can write this:
- result = Helper.Eval(() => a.b.c.d, null);
As an aside, it's really annoying not being able to write something like this:
- public static T Something<T>(Func<T[]> func)
instead of writing say 5 overloads for Func<T> to Func<T1, T2, T3, T4, T>.
Comments