Is null internally represented as 0 for integer types?

  • Thread starter Thread starter Raj
  • Start date Start date
R

Raj

int?[] nums=new int?[2];
nums[0]=100;
nums[1]=null;

nums[0].GetHashCode returns 100
Why is nums[1].GetHashCode returns 0?

Thank you

Regards
Raj
 
Raj said:
int?[] nums=new int?[2];
nums[0]=100;
nums[1]=null;

nums[0].GetHashCode returns 100
Why is nums[1].GetHashCode returns 0?

Thank you

Regards
Raj

Yes and no. A null for a nullable type is internally represented by
setting a flag to false, which in turn is internally represented as
zero. But it's the flag that is zero, not the value.

The flag is stored separately from the value. When the flag is false,
the value is unreachable, and the only way to set the flag to true is to
assign a new value to the variable.

When the flag is true, the hash code that is returned is determined from
the value only. When the flag is false, the hash code returned is a
specific predefined value which happens to be chosen as zero. It could
have been any value.

For a nullable int, the hash code for null and 0 happens to be the same,
but this is not a problem. As all possible values can be returned as
hash code when the nullable has a value, there is no special hash code
that can be reserved for the null state, so it has to be the same hash
code as one returned by some value. The value zero is as good as any other.
 
Back
Top