Reputation: 776
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.
Upvotes: 16
Views: 13931
Reputation: 3698
You can use this extension method:
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);
Upvotes: 2
Reputation: 14318
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)
Upvotes: 4
Reputation: 69372
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).
Upvotes: 13
Reputation: 7894
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
Upvotes: 7