Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling property chains that could contain nulls

I have some code that is extracting a value at the end of a long property chain where any one of the properties could be null.

For example:

var value = prop1.prop2.prop3.prop4;

In order to handle the possibility of null in prop1 I have to write:

var value = prop1 == null ? null : prop1.prop2.prop3.prop4;

In order to handle the possibility of null in prop1 and prop2 I have to write:

var value = prop1 == null 
            ? null 
            : prop1.prop2 == null ? null : prop1.prop2.prop3.prop4;

or

var value = prop1 != null && prop1.prop2 != null 
            ? prop1.prop2.prop3.prop4 
            : null;

If I want to handle the possibility of null in prop1, prop2 and prop3 as well, or even longer property chains, then the code starts getting pretty crazy.

There must be a better way to do this.

How can I handle property chains so that when a null is encountered, null is returned?

Something like the ?? operator would be great.

like image 503
John Mills Avatar asked Jan 21 '23 01:01

John Mills


1 Answers

Update

As of C# 6, a solution is now baked into the language with the null-conditional operator; ?. for properties and ?[n] for indexers.

The null-conditional operator lets you access members and elements only when the receiver is not-null, providing a null result otherwise:

int? length = customers?.Length; // null if customers is null
Customer first = customers?[0];  // null if customers is null

Old Answer

I had a look at the different solutions out there. Some of them used chaining multiple extension method calls together which I didn't like because it wasn't very readable due to the amount of noise added for each chain.

I decided to use a solution that involved just a single extension method call because it is much more readable. I haven't tested for performance, but in my case readability is more important than performance.

I created the following class, based loosely on this solution

public static class NullHandling
{
    /// <summary>
    /// Returns the value specified by the expression or Null or the default value of the expression's type if any of the items in the expression
    /// return null. Use this method for handling long property chains where checking each intermdiate value for a null would be necessary.
    /// </summary>
    /// <typeparam name="TObject"></typeparam>
    /// <typeparam name="TResult"></typeparam>
    /// <param name="instance"></param>
    /// <param name="expression"></param>
    /// <returns></returns>
    public static TResult GetValueOrDefault<TObject, TResult>(this TObject instance, Expression<Func<TObject, TResult>> expression) 
        where TObject : class
    {
        var result = GetValue(instance, expression.Body);

        return result == null ? default(TResult) : (TResult) result;
    }

    private static object GetValue(object value, Expression expression)
    {
        object result;

        if (value == null) return null;

        switch (expression.NodeType)
        {
            case ExpressionType.Parameter:
                return value;

            case ExpressionType.MemberAccess:
                var memberExpression = (MemberExpression)expression;
                result = GetValue(value, memberExpression.Expression);

                return result == null ? null : GetValue(result, memberExpression.Member);

            case ExpressionType.Call:
                var methodCallExpression = (MethodCallExpression)expression;

                if (!SupportsMethod(methodCallExpression))
                    throw new NotSupportedException(methodCallExpression.Method + " is not supported");

                result = GetValue(value, methodCallExpression.Method.IsStatic
                                             ? methodCallExpression.Arguments[0]
                                             : methodCallExpression.Object);
                return result == null
                           ? null
                           : GetValue(result, methodCallExpression.Method);

            case ExpressionType.Convert:
                var unaryExpression = (UnaryExpression) expression;

                return Convert(GetValue(value, unaryExpression.Operand), unaryExpression.Type);

            default:
                throw new NotSupportedException("{0} not supported".FormatWith(expression.GetType()));
        }
    }

    private static object Convert(object value, Type type)
    {
        return Expression.Lambda(Expression.Convert(Expression.Constant(value), type)).Compile().DynamicInvoke();
    }

    private static object GetValue(object instance, MemberInfo memberInfo)
    {
        switch (memberInfo.MemberType)
        {
            case MemberTypes.Field:
                return ((FieldInfo)memberInfo).GetValue(instance);
            case MemberTypes.Method:
                return GetValue(instance, (MethodBase)memberInfo);
            case MemberTypes.Property:
                return GetValue(instance, (PropertyInfo)memberInfo);
            default:
                throw new NotSupportedException("{0} not supported".FormatWith(memberInfo.MemberType));
        }
    }

    private static object GetValue(object instance, PropertyInfo propertyInfo)
    {
        return propertyInfo.GetGetMethod(true).Invoke(instance, null);
    }

    private static object GetValue(object instance, MethodBase method)
    {
        return method.IsStatic
                   ? method.Invoke(null, new[] { instance })
                   : method.Invoke(instance, null);
    }

    private static bool SupportsMethod(MethodCallExpression methodCallExpression)
    {
        return (methodCallExpression.Method.IsStatic && methodCallExpression.Arguments.Count == 1) || (methodCallExpression.Arguments.Count == 0);
    }
}

This allows me to write the following:

var x = scholarshipApplication.GetValueOrDefault(sa => sa.Scholarship.CostScholarship.OfficialCurrentWorldRanking);

x will contain the value of scholarshipApplication.Scholarship.CostScholarship.OfficialCurrentWorldRanking or null if any of the properties in the chains return null along the way.

like image 184
John Mills Avatar answered Jan 28 '23 08:01

John Mills