Nullable value types¶
Some value types (like int, float, bool, etc.) cannot have a null
value by default. However, sometimes you might want to represent the absence of a value, especially when working with databases or optional fields.
To allow value types to hold null, C# provides nullable value types using ?
:
How it works internally¶
A nullable value type (T?
) is actually a struct called Nullable<T>
. This struct has two properties:
HasValue
– Returns true if the variable has a value.
Value
– Retrieves the actual value if HasValue is true.
int? i = null;
is the same as nullable<int> i = null;
.
Null-Coalescing Operator (??
)¶
Instead of checking HasValue, you can provide a default value using ??
:
Null-Conditional Operator (?.
)¶
You can also use null-conditional access (?.
) to safely handle nullable types:
Explicitly Converting Nullable to Non-Nullable¶
If you directly assign a nullable type to a non-nullable type, it will cause a compilation error unless you explicitly handle null cases.