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.
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.
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.
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.
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.
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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With