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






4.88/5 (12 votes)
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.