Wednesday, January 07, 2009

Returning a default value in case of errors

Ever wrote something like this?

  1. if (a != null && a.b != null && a.b.c != null)  
  2.   result = a.b.c.d;  
  3. else  
  4.   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:

  1. public static T Eval<T, ExceptionClass>(Func<T> func, Func<ExceptionClass, T> onError)  
  2.   where ExceptionClass: Exception  
  3. {  
  4.   try  
  5.   {  
  6.     return func();  
  7.   }  
  8.   catch (ExceptionClass e)  
  9.   {  
  10.     return onError(e);  
  11.   }  
  12. }  
  13.   
  14. public static T Eval<T>(Func<T> func, Func<Exception, T> onError)  
  15. {  
  16.   return Eval<T, Exception>(func, onError);  
  17. }  
  18.   
  19. public static T Eval<T>(Func<T> func, T defaultValue)  
  20. {  
  21.   return Eval<T, Exception>(func, e => defaultValue);  
  22. }  


Now I can write this:

  1. result = Helper.Eval(() => a.b.c.d, null);  


As an aside, it's really annoying not being able to write something like this:

  1. public static T Something<T>(Func<T[]> func)  


instead of writing say 5 overloads for Func<T> to Func<T1, T2, T3, T4, T>.

No comments: