Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Beware: The null-coalescing (??) operator is low in the order of operator precedence.

0.00/5 (No votes)
4 Feb 2014 1  
Maybe writing a tip will mean the last time I fall for this.

Introduction

One of my favourite operators is the null-coalescing, or ?? operator.  It is used with a nullable type to evaluate to a non-null value when the nullable value is null.  For example: 

Background

int? foo = null; 
int bar = foo ?? 7;
// bar == 7
It is a shorthand for:
int? foo = null; 
int bar = foo == null ? 7 : foo;
// bar == 7

Order of Operator Precedence

It is important, however, to keep in mind the order of operator precedence:

int? top = 60;
int? bottom = 180;
int height = bottom ?? 0 - top ?? 0;

// So height == 120?
Nope. When you look at this code, it seems like it should be evaluated like:
int? top = 60;
int? bottom = 180;
int height = (bottom ?? 0) - (top ?? 0);

// height == 120
However, it is actually evaluated:
int? top = 60;
int? bottom = 180;
int height = bottom ?? (0 - top ?? 0);

// height == 180

This is caused me wasted debugging time on more than one occasion.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here