开发者

Why value types can't be null

I know that it is possible to have Nullable value types that wraps the value type and gives ability to stor开发者_StackOverflow社区e null. But is there a technical reason do not allow the value type to be null or the reason is only conceptual?


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜