Search code examples
c#nullableoperator-precedenceevaluationnull-coalescing-operator

How to explain null-coalescing expression precedence evaluation with some operators?


The following code works fine. What is the logic behind the addition + being evaluated after the null-coalescing ??? How's that possible? Where is the doc explaining that?

    int? tNullable = 2;
    public int TestNullCoalescing()
    {
        int t = 7;
        t = tNullable + 1 ?? t;
        Debug.Assert(t == 3);
        tNullable = null;
        t= 7;
        t = tNullable + 1 ?? t;
        Debug.Assert(t == 7);

References:

  1. ?? and ??= operators - the null-coalescing operators
  2. 12.15 The null coalescing operator

Solution

  • Because null + 1 is still null (the + 1 is not even calculated), the ?? operator directly returns 7.