Why value types can't be null

后端 未结 2 1563
你的背包
你的背包 2020-12-16 13:32

I know that it is possible to have Nullable value types that wraps the value type and gives ability to store null. But is there a technical reason do not allow the value ty

相关标签:
2条回答
  • 2020-12-16 13:48

    A reference type is storeed as a reference (like a pointer) to an object instance.
    null means a reference that isn't pointing to an instance of an object.

    Value types are stored as the values themselves, without any references.
    Therefore, it doesn't make sense to have a null value type—the value type by definition contains a value.

    Nullable<T> is a value type with a HasValue flag that can be false to indicate that there is no value. It still has a value (when HasValue is false, Value is default(T)), but the HasValue flag tells you to ignore the value.
    It has nothing to do with null, except that the CLR automatically unboxes null boxed values to a Nullable<T> with HasValue set to false.

    0 讨论(0)
  • 2020-12-16 13:59

    A value type like 'Int32' is stored using thirty-two bits of storage. There are precisely 4,294,967,296 values that may be represented by 32 bits, and an Int32 can hold 4,294,967,296 different values. If -2,147,483,648 were not a valid Int32 value, it might be possible to use that to represent "null", but the fact that its binary representation isn't all zeroes would complicate things. By contrast, the number of possible bit combinations in a reference type far exceeds the number of possible valid references, so there's no difficulty reserving a bit combination to represent "null".

    0 讨论(0)
提交回复
热议问题