.NET – Why Intrinsic Data Types Can’t Be Null

net

First the history:

I found out DateTime data types cannot be null (Yes they can be nullable using the ? nullable declaration).

I was told this is because they are value types and placed on the stack (not on the heap).

I can understand why the stack is quicker and why value types need to (mostly) be placed on the stack, what I do not know is.

  1. Is it true the real limitation of why a value type cannot be null is because the stack cannot handle null values?

  2. If yes – Why? If No what is the real limitation.

I understand in .net we often don't care about exact memory allocation, yet it is important in performance applications to take the stack and heap into consideration, so I'm trying to wrap my head around this.

Thanks in advance for your expertise on a difficult question.

EDIT: Another thing to add are nullable types hence placed on the heap or stack?

Best Answer

The heap and stack are not relevant. It is about Binary representation of values.

In a reference type, a zero binary representation means null, and other binary representations point to memory that contains the binary representation of the value.

In a value type, all binary representations, including zero, directly represent a particular value of the type. Value types cannot be null because there is no reserved binary representation that means null.

Related Topic