Usually you can't assign null to value types, such as
DateTime, etc. You can make them nullable by adding
? symbol after type declaration of variable/field/property:
int? nullableNumber = null;
nullableNumber become reference variable?
Nullable type are neither value type nor reference type. Nullable is a
struct, but it has few differences from usual structs. The nullable struct has two properties:
- Property with the value of the data type (
- A boolean property which tells if the data type value has been set (
When you set the value nullable variable, the struct changes
Since nullable type is a
struct, it's definetly not a reference type. But since nullable can be assigned
null value, a nullable type cannot satisfy a struct constraint in generics. Also, when you box a nullable type with
HasValue equal to
false, you get a null pointer instead of a boxed nullable type:
bool? b = null; object o = b; // Now o is null.
If the object is non-null (
true), then boxing occurs, but only the underlying type that the nullable object is based on is boxed. Boxing a non-null nullable value type boxes the value type itself, not the
System.Nullable<T> that wraps the value type:
bool? b = false; object bBoxed = b; // bBoxed contains a boxed bool.
This makes nullable kind of it's own type with behavior different from both reference and value types.
- Nullable variable is a
structbut with few differences: it has two properties and can't satisfy struct constraint in generics.
- Nullable variable is not a reference type, although it can be assigned
- Boxing a non-null nullable value type boxes the value type itself, not the
System.Nullable<T>that wraps the value type.