Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3431610
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 18, 20262026-05-18T07:20:50+00:00 2026-05-18T07:20:50+00:00

I have some code that is extracting a value at the end of a

  • 0

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.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-18T07:20:51+00:00Added an answer on May 18, 2026 at 7:20 am

    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.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

No related questions found

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.