Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 997
Pal Avatar asked Jul 30 '13 09:07

Pal


People also ask

What happens if you cast null to int?

In other words, null can be cast to Integer without a problem, but a null integer object cannot be converted to a value of type int.

Can a nullable be null?

Conversion from a nullable value type to an underlying type At run time, if the value of a nullable value type is null , the explicit cast throws an InvalidOperationException.

What is difference between null and nullable?

Technically a null value is a reference (called a pointer in some languages) to an empty area of memory. Reference variables (variables that contain an address for data rather than the data itself) are always nullable , which means they are automatically capable of having a null value.

What is the difference between nullable int and int?

No difference. int? is just shorthand for Nullable<int> , which itself is shorthand for Nullable<Int32> . Compiled code will be exactly the same whichever one you choose to use.


2 Answers

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).

like image 87
keyboardP Avatar answered Oct 07 '22 06:10

keyboardP


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

like image 8
Denys Denysenko Avatar answered Oct 07 '22 06:10

Denys Denysenko