Can structs really not be null in C#?
Because you're not actually setting the Nullable<T>
variable to null
. The struct is still there. It represents null
via an internal bit flag in the struct.
There's also some compiler sugar to make magic happen behind the scenes.
You can't set a structure to null, but you can have implicit type conversions, which is what is happening under the hood.
C# has some syntax sugar that allows you to appear to set a nullable type to null
. What you are actually doing under the covers is setting the nullable type's HasValue
property to false
.
The C# compiler provides you with a bit of sugar so you really are doing this:
Nullable<bool> b = new Nullable<bool>();
Here is the syntactic sugar
bool? b = null;
if (b ?? false)
{
b = true;
}