Search code examples
c#nullreferenceexceptionnullablenull-conditional-operator

C# elegant way to check if a property's property is null


In C#, say that you want to pull a value off of PropertyC in this example and ObjectA, PropertyA and PropertyB can all be null.

ObjectA.PropertyA.PropertyB.PropertyC

How can I get PropertyC safely with the least amount of code?

Right now I would check:

if(ObjectA != null && ObjectA.PropertyA !=null && ObjectA.PropertyA.PropertyB != null)
{
    // safely pull off the value
    int value = objectA.PropertyA.PropertyB.PropertyC;
}

It would be nice to do something more like this (pseudo-code).

int value = ObjectA.PropertyA.PropertyB ? ObjectA.PropertyA.PropertyB : defaultVal;

Possibly even further collapsed with a null-coalescing operator.

EDIT Originally I said my second example was like js, but I changed it to psuedo-code since it was correctly pointed out that it would not work in js.


Solution

  • In C# 6 you can use the Null Conditional Operator. So the original test will be:

    int? value = objectA?.PropertyA?.PropertyB?.PropertyC;