Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this bitwise OR return null on a nullable int?

Tags:

c#

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.

like image 447
Grant H. Avatar asked Jun 11 '13 17:06

Grant H.


People also ask

How do I assign a null to a Nullable integer?

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.

What is default value of Nullable int?

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 .

Can we compare int with null?

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.

How do you make an int Nullable in C#?

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.


1 Answers

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 type T?. These operators, also known as lifted operators, produce null if one or both operands are null; otherwise, the operator uses the contained values of its operands to calculate the result.

like image 152
Oliver Charlesworth Avatar answered Oct 10 '22 12:10

Oliver Charlesworth