Tuesday, December 30, 2008

Call a method only if a supplied argument is not Null

Suppose you have a C# method which only works correctly if its parameter value is not Null, otherwise it either throws an exception or returns wrong value. Sometimes you cannot guarantee that a parameter value is not Null, because it was passed from outside, was read from DB, etc. Instead of writing your custom code again and again, which checks a parameter value and only calls a method if it is not Null, it may be more convenient to re-use a common helper method. Overloaded CallIfArgumentNotNull() methods shown below are such helpers. I was somehow inspired by reading this article by Jon Skeet (lazy evaluation) .

    // If a first argument of type int? is not Null, a supplied method (second argument)
    // is called with a first argument passed in and its return value is returned.
    // If a first argument is Null, a default(T) is returned
    // (null for reference types, 0 from Integer, etc.)
    public static T CallIfArgumentNotNull<T>(int? arg, Func<int, T> func) {
      return (arg != null) ? func((int)arg) : default(T);
    }
 
    // If a first argument of type int? is not Null, a supplied method (second argument)
    // is called with a first argument passed in and its return value is returned.
    // If a first argument is Null, a third argument value is returned.
    public static T CallIfArgumentNotNull<T>(int? arg, Func<int, T> func, T defResult) {
      return (arg != null) ? func((int)arg) : defResult;
    }
 
    // If a first argument of type A? is not Null, a supplied method (second argument)
    // is called with a first argument passed in and its return value is returned.
    // If a first argument is null, a third argument value is returned.
    public static T CallIfArgumentNotNull<A, T>(Nullable<A> arg, Func<A, T> func, T defResult)
      where A : struct {
      return (arg != null) ? func((A)(arg)) : defResult;
    }