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 type to be null or the reason is only conceptual?
As you know, a value type cannot be assigned a null value. For example, int i = null will give you a compile time error. C# 2.0 introduced nullable types that allow you to assign null to value type variables.
In other words NULL is undefined. Primitive types such as integers and Booleans cannot generally be null, but the corresponding nullable types (nullable integer and nullable Boolean, respectively) can also assume the NULL value. This can be represented in ternary logic as FALSE,NULL,TRUE as in three-valued logic.
Nullable variables may either contain a valid value or they may not — in the latter case they are considered to be nil . Non-nullable variables must always contain a value and cannot be nil . In Oxygene (as in C# and Java), the default nullability of a variable is determined by its type.
A NULL value is a special marker used in SQL to indicate that a data value does not exist in the database. In other words, it is just a placeholder to denote values that are missing or that we do not know. NULL can be confusing and cumbersome at first. But it is imperative for any analyst to know how to handle them.
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".
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