Search code examples
c#operatorsnullable

Why nullable int (int?) doesn't increase the value via "+=" if the value is NULL?


I have a page counter type of int?:

spot.ViewCount += 1;

It works ONLY if the value of ViewCount property is NOT NULL (any int).

Why the compiler do so?

I would be grateful for any solutions.


Solution

  • If you'll look into what compiler has produced for you then you'll see the internal logic behind.

    The code:

    int? i = null;
    i += 1;
    

    Is actually threated like:

    int? nullable;
    int? i = null;
    int? nullable1 = i;
    if (nullable1.HasValue)
    {
        nullable = new int?(nullable1.GetValueOrDefault() + 1);
    }
    else
    {
        int? nullable2 = null;
        nullable = nullable2;
    }
    i = nullable;
    

    I used JustDecompile to get this code