Handling null

Topics: General
Sep 22, 2011 at 7:00 AM
Edited Sep 22, 2011 at 7:16 AM

How can null be handled? in expression 5+[myCustomValue] if parameter [myCustomValue] returns null. Expression ends up in exception. Can null be evaluated to 0 in calculation and false in logical expression

Jul 20, 2014 at 9:12 PM
Edited Jul 20, 2014 at 9:30 PM
I'm late to the party but just in case someone else is having the same issue then I solved it by adding a null check for both values being compared so it only does a direct comparison instead of using .GetType() which obviously causes an error. Here's how the function CompareUsingMostPreciseType should look like after that:
        public int CompareUsingMostPreciseType(object a, object b)
        {
            if (a == null || b == null)
                return a == b ? 0 : 1;
        
            Type mpt = GetMostPreciseType(a.GetType(), b.GetType());
            return Comparer.Default.Compare(Convert.ChangeType(a, mpt), Convert.ChangeType(b, mpt));
        }
Also make sure you add a parameter that equals null so it can be used in your formula. In my case I'm simply calling "null":
            expr.Parameters.Add("null", null);
Finally since you can't directly add an integer to a null value you'll need to rewrite your formula by making use of the "if" statement:
 if([myCustomValue] == null, 0, 5+[myCustomValue])