Search code examples
c#nullablenull-coalescing

How to translate "var a = collection?.First()?.somePropA ?? new A();"


What is the purpose of single question mark on the right side of assignment in expression with null-coalescing operator? Example:

var a = collection?.First()?.somePropA ?? new A();

Solution

  • The single quotation mark (?.) is newly added in C# 6.0 and represents a null check.

    So, for example, the following code is the same;

    var foo = bar?.bar2;
    

    Or

    var foo = null;
    if (bar != null)
        foo = bar.bar2;
    else
        foo = null;
    

    However, both can still return null. Therefore one can use the ?? check to assign a value if the result indeed is null.

    That being said, one can write the following code;

    var foo = bar?.bar2 ?? new Bar2();
    

    which is basically the same as

    var foo = null;
    if (bar != null)
        foo = bar.bar2;
    else
        foo = new Bar2();
    

    Using ?. multiple times can really shorten your code. Consider, for example, the following line;

    var foo = bar?.bar2?.bar3?.bar4?.bar5 ?? new Bar5();
    

    this is syntactic sugar for

    var foo = null;
    if (bar != null)
    {
        if (bar.bar2 != null)
        {
            if (bar.bar2.bar3 != null)
            {
                if (bar.bar2.bar3.bar4 != null)
                {
                    if (bar.bar2.bar3.bar4.bar5 != null)
                        foo = bar.bar2.bar3.bar4.bar5;
                    else
                        foo = new Bar5();
                }
                else
                    foo = new Bar5();
            }
            else
                foo = new Bar5();
        }
        else
            foo = new Bar5();
    }
    else
        foo = new Bar5();
    

    Of course, there are already way better ways to write the above (for example, by initializing foo = new Bar5() before doing all the checks), but for clarity I kept it this way.