Nullable Types in C#
Introduction to Nullable Types
In C#, **value types** (such as int
, float
, bool
) must always have a value.
However, in **certain scenarios**, such as **database operations** or **optional values**, you may need to represent **'no value' or null**.
**Nullable types** allow value types to **store a null value**.
Declaring a Nullable Type:
int? nullableInt = null;
Here, **nullableInt
can either store an integer value or null
**.
Checking Nullable Values
You can **check if a nullable type contains a value** using the **.HasValue
property**
and **retrieve the value** using the **.Value
property**.
Example: Checking Nullable Type
int? nullableInt = 5;
if (nullableInt.HasValue)
{
Console.WriteLine("Value: " + nullableInt.Value);
}
else
{
Console.WriteLine("No value assigned");
}
If nullableInt
has a value, it is printed using **.Value
**.
Otherwise, it prints "No value assigned".
Using the Null-Coalescing Operator (??)
The **null-coalescing operator (??
)** allows assigning a **default value**
when a nullable type is **null**.
Example: Null-Coalescing Operator
int? nullableNumber = null;
int defaultValue = nullableNumber ?? 100; // Assigns 100 if null
Console.WriteLine(defaultValue); // Output: 100
The **null-coalescing operator** ensures that if nullableNumber
is **null**,
a **default value (100) is assigned** instead.
Nullable Types in Database Operations
When fetching data from a **database**, some fields may contain **null values**. Using nullable types prevents **runtime errors** in such cases.
Example: Handling Nullable Database Values
int? age = GetAgeFromDatabase(); // Function that might return null
int displayAge = age ?? -1; // Assign -1 if null
Console.WriteLine("User Age: " + displayAge);
Here, **GetAgeFromDatabase()
might return null**,
so we use **??
to assign -1 as a fallback value**.
Nullable Operators in C#
C# provides **special operators** for working with **nullable types**:
Operator | Description | Example |
---|---|---|
? |
Declares a nullable type | int? num = null; |
.HasValue |
Checks if a nullable type has a value | if (num.HasValue) { } |
.Value |
Retrieves the actual value | int x = num.Value; |
?? |
Provides a default value | int x = num ?? 0; |
Best Practices for Using Nullable Types
- Use Nullable Types for Optional Values: If a value **is not always required**, declare it as **nullable**.
- Always Use
??
Operator: Prevents **null reference exceptions** by assigning a **default fallback value**. - Avoid Unnecessary Nullable Assignments: If a **value is always required**, don’t make it nullable.
- Check for
.HasValue
Before Using: Avoid **null exceptions** when accessing `.Value`. - Use Nullable Reference Types (C# 8.0+): Enable **null safety** for reference types like **strings**.