Showing posts with label operators. Show all posts
Showing posts with label operators. Show all posts

Saturday, 27 April 2013

The curious case of null coalescing arithmetic

or how the simple things trip you up

I was writing a quick bit of code to add two nullable integers. To cope with the null, I used the wonderfully simple null coalescing operator ?? in C# to convert the integers to zero, like this:
int result = a ?? 0 + b ?? 0;
The result was wrong as demonstrated below:
int? a = 2;
int? b = 4;

int c = a ?? 0 + b ?? 0;
// Result:
// c = 2;
The obvious answer was a problem with operator precedence and a few brackets later fixed the problem:
int c = (a ?? 0) + (b ?? 0);
// Result:
// c = 6;
But why was it doing in the first instance? A little playing with linqpad later and it turns out the + operator has a much higher precedence than ??, so it was actually doing:
int c = a ?? ((0 + b) ?? 0);
This reads as: a, or if a is null then 0 + b, if 0 + b is null then zero. The mistake I made was because I'm so used to using ?? as a simple substitution of the preceding variable I wasn't thinking of it as a 'real' operator with precedence and ordering.