Search code examples
c#null-coalescing-operatornull-check

Is there a shorter way to write this inline if?


Hey guys is there a shorter way to write this line.

int objectID = jsonObject != null && jsonObject.ObjectID.HasValue && jsonObject.ObjectID.Value > 0 ? jsonObject.ObjectID.Value : defaultObject.ObjectID;

//jsonObject.ObjectID is int?

Can u use a null coalesce to check null and > 0?


Solution

  • Something like this, it takes advantage of null conditional and lifted operators

    int objectID = jsonObject?.ObjectID > 0 ? jsonObject.ObjectID.Value : defaultObject.ObjectID;
    

    Note : This assumes defaultObject.ObjectID is an int and not an int?