Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Nullable integers – why does it not throw an exception?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading