13

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.

Pal
  • 756
  • 2
  • 10
  • 20

4 Answers4

11

Null is not the same as 0. Therefore, there's no logical operation that will increase null to an int value (or any other value type). If you want to increase the value of a nullable int from null to 1, for example, you could do this.

int? myInt = null;
myInt = myInt.HasValue ? myInt += 1 : myInt = 1;

//above can be shortened to the below which uses the null coalescing operator ??
//myInt = ++myInt ?? 1

(although remember that this isn't increasing null, it's just achieving the effect of assigning an integer to a nullable int value when it's set as null).

keyboardP
  • 68,824
  • 13
  • 156
  • 205
8

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

Denys Denysenko
  • 7,598
  • 1
  • 20
  • 30
3

Because nullable types have lifted operators. Generally, it's a specific case of function lifting in C# (or at least it looks like it is, correct me if I'm wrong).

Which means that any operation with null will have a null result (e.g 1 + null, null * null etc)

snipsnipsnip
  • 2,268
  • 2
  • 33
  • 34
Patryk Ćwiek
  • 14,078
  • 3
  • 55
  • 76
1

You can use these extension methods:

public static int? Add(this int? num1, int? num2)
{
    return num1.GetValueOrDefault() + num2.GetValueOrDefault();
}

Usage:

spot.ViewCount = spot.ViewCount.Add(1);

Or even:

int? num2 = 2; // or null
spot.ViewCount = spot.ViewCount.Add(num2);
Jacob
  • 3,598
  • 4
  • 35
  • 56
  • You don't need to write a custom extension method to get a nullable's value, or it's default value if there is no value. `Nullable` already has that method, `GetValueOrDefault`. – Servy Dec 06 '17 at 18:36
  • @Serv Good point, I changed it. However, defining another extension method is not a mistake and especially not deserve a down vote. – Jacob Dec 06 '17 at 18:46