Nullable Value Types
int? and the Nullable struct.
Why Nullable Value Types?
Value types like int, bool, and DateTime always hold a value. An int defaults to 0, never "no value".
Sometimes you need to represent missing data, such as an unanswered survey field or an empty database column. Nullable value types let a value type also hold null.
Declaring with int?
Add a ? after a value type to make it nullable. int? can hold any integer or null.
This is the most common way you will write nullable value types in everyday C# code.
int? age = null;
int count = 5;
age = count;
System.Console.WriteLine(age);All lessons in this course
- Nullable Value Types
- Null-Conditional Operator
- Null-Coalescing Operators
- Guarding Against Nulls