Math operations with null

From MSDN:

The predefined unary and binary operators and any user-defined operators that exist for value types may also be used by nullable types. These operators produce a null value if the operands are null; otherwise, the operator uses the contained value to calculate the result.

That's why all the test are passed, including the last one - no matter what the operand value is, if another operand is null, then the result is null.


The operators for Nullable<T> are so-called "lifted" operators]; the c# compiler takes the operators available for T and applies a set of pre-defined rules; for example, with +, the lifted + is null if either operand is null, else the sum of the inner values. Re the last; again, division is defined as null if either operand is null - it never performs the division.


I tried seeing the generated code from the code below using reflector

var myValue = 10 / null;

And the compiler turns it into this:

int? myValue = null;

And this wont compile, so you cant trick it:

object myNull = null;
var myValue = 10 / myNull;

I would assume that the compiler converts zero to Nullable<int>, and provides the underlying division operator. Since the Nullable type may be null, the division by 0 is not caught during compile. Best guess is that they want you to be able to do null testing in cases where div/0 is occuring.

Tags:

C#