I’m not sure if this is a bug or intended by design but I was hoping someone here would have more of an idea as to why it happens.
Consider this code
var someMetric = GetMetric(); // returns 3000
var someNullableMetric = GetNullableMetric(); // returns null
// Doesn't work
var total = someMetric + someNullableMetric; // why does this return null and not throw an error?
var Total = someMetric + someNullableMetric ?? 0; // why is '+' done prior to '??'
// Works
var Total = someMetric + (someNullableMetric ?? 0); // this understandably works
Just looking for an explanation as this functionality was totally unexpected, null coalescing operator doesn’t fall into BODMAS so I would have assumed it would have been executed first (although last kind makes more sense now I’m typing it out)? or an exception would have been thrown for trying to add null to a value.
>Solution :
Both of these follow the documented rules of C#.
someMetric + someNullableMetric evaluates to null due to lifted operators. If you want to force an exception, you can always use someMetric + someNullableMetric.Value instead. See the spec section 12.4.8 for more details.
someMetric + someNullableMetric ?? 0 is equivalent to (someMetric + someNullableMetric) ?? 0 because + has higher precedence than ??.
If you want an exception, use someNullableMetric.Value. If you don’t want an exception, use (someNullableMetric ?? 0) as per the last line of your question’s code. See spec section 12.4.2 for more details.