Today’s article is about a few surprising behaviors that I’ve stumbled upon lurking in the C# language and its libraries. I wouldn’t go as far as to call them bugs, but they’re the sort of things that can catch you off guard if you’re not careful.
Nullable Math
The first of these concerns nullable integers. Integers in C# are integral numeric types, and ordinarily they would have a default value of zero. By making them nullable, their default value becomes null
, and when you use null
in a mathematical expression, the result is always null
. There’s actually a compiler warning for this, CS0458, which you’ll see if you write something like: int? i = 1 + null;
. However, there is no such compiler warning when using the increment operator ++
.
void Main()
{
var point = new Point();
point.X++; // X is still null
}
class Point
{
public int? X { get; set; }
public int? Y { get; set; }
}
At the end of the Main
method the value of point.X
is going to be null
, not 1, and there is no compiler warning.
Even simplifying the code to something like this leaves no warning and a result of null
:
int? i = null;
i++; // i is still null, not 1.