Letβs go through nullable types in C# β a way to allow value types to represent null
.
π 1. What Are Nullable Types?
-
Normally, value types like
int
,double
,bool
cannot be null. -
Nullable types allow these types to also have a null value, useful for optional data or database mapping.
π 2. Syntax
There are two ways to declare nullable types:
int? nullableInt = null; // Using ?
Nullable<int> anotherInt = null; // Using Nullable<T>
-
int?
is shorthand forNullable<int>
-
Works with all value types (
int
,double
,bool
,DateTime
, etc.)
π 3. Checking for Value
Use .HasValue
or compare to null
:
int? age = null;
if (age.HasValue)
Console.WriteLine("Age: " + age.Value);
else
Console.WriteLine("Age is not provided"); // Output
-
.Value
gives the actual value -
Accessing
.Value
when null throws InvalidOperationException
π 4. Using Null-Coalescing Operator (??
)
- Provides a default value if the nullable is null
int? age = null;
int displayAge = age ?? 18; // If age is null, use 18
Console.WriteLine(displayAge); // 18
π 5. Nullable Boolean Example
bool? isActive = null;
if (isActive == true)
Console.WriteLine("Active");
else if (isActive == false)
Console.WriteLine("Inactive");
else
Console.WriteLine("Status unknown"); // Status unknown
- Nullable booleans allow three states:
true
,false
,null
π 6. Nullable in Expressions
int? a = 5;
int? b = null;
int? sum = a + b; // sum is null because b is null
- Arithmetic operations propagate
null
if any operand is null
π 7. Summary Table
Feature | Description |
---|---|
Syntax | int? x or Nullable<int> x |
Checking for value | x.HasValue or x != null |
Accessing value | x.Value |
Default value | x ?? defaultValue |
Use Case | Optional data, database fields, three-state logic (e.g., nullable bool) |
β Tip:
-
Use nullable types for optional fields or database-mapped value types
-
Combine with null-coalescing (
??
) and null-conditional (?.
) operators for clean code