C# okay with comparing value types to null

This is legal because operator overload resolution has a unique best operator to choose. There is an == operator that takes two nullable ints. The int local is convertible to a nullable int. The null literal is convertible to a nullable int. Therefore this is a legal usage of the == operator, and will always result in false.

Similarly, we also allow you to say “if (x == 12.6)”, which will also always be false. The int local is convertible to a double, the literal is convertible to a double, and obviously they will never be equal.

Leave a Comment