Search code examples
c#null-coalescing-operator

Null-coalescing operator and order of operations?


Can anyone explain to me why this code:

int? a = 54;
decimal b = a ?? 0 / 100m;

b has the value of 54 ?

But if I add some brackets:

int? a = 54;
decimal b = (a ?? 0) / 100m;

It has the value of 0.54?

I don't understand why this is the case. Because a has the value of 54 I would have thought the ?? operator would do nothing.


Solution

  • From MSDN:

    The null-coalescing operator ?? returns the value of its left-hand operand if it isn't null; otherwise, it evaluates the right-hand operand and returns its result. The ?? operator doesn't evaluate its right-hand operand if the left-hand operand evaluates to non-null.

    In your first case,

    int? a = 54;  //Here "a" is not null
    decimal b = a ?? 0 / 100m; //As "a" is not null, Value of "a" will be assigned to "b".
    

    In your second case ,

      // precedence of "(<expression>)" is greater than "null coalescing operator" 
      int b = (a ?? 0) / 100m;
              //+++++++        --This will evaulate first and returns 54
             //          +++  -- This will be calculated as 54 / 100m i.e 0.54