I essentially have the following:
int? myVal = null;
myVal |= 1;
bool stillNull = myVal == null; //returns true
Why does this behave this way? My understanding of bitwise operator/operand behavior is not terribly strong, and I could not find a reason that it wouldn't be treated as a simple assignment in this case.
You can declare nullable types using Nullable<t> where T is a type. Nullable<int> i = null; A nullable type can represent the correct range of values for its underlying value type, plus an additional null value. For example, Nullable<int> can be assigned any value from -2147483648 to 2147483647, or a null value.
flag = null; // An array of a nullable value type: int?[] arr = new int?[10]; The default value of a nullable value type represents null , that is, it's an instance whose Nullable<T>. HasValue property returns false .
Some int value as an int? is definitely non-null and null is definitely null. The compiler realizes that and since a non-null value is not equal to a definite null value, the warning is given. The compiler also optimizes this away because it is always false. It won't even load the x variable at all.
C# 2.0 introduced nullable types that allow you to assign null to value type variables. You can declare nullable types using Nullable where T is a type. Nullable types can only be used with value types. The Value property will throw an InvalidOperationException if value is null; otherwise it will return the value.
From the documentation:
The predefined unary and binary operators or any overloaded operators that are supported by a value type
T
are also supported by the corresponding nullable value typeT?
. These operators, also known as lifted operators, producenull
if one or both operands arenull
; otherwise, the operator uses the contained values of its operands to calculate the result.
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