Nullable Types in C#
What are Nullable Types?
In C#, all value types (such as int
, float
, bool
) must have a value. However, there are scenarios where a value type needs to represent "no value" or null
, especially when dealing with databases or optional values.
This is where nullable types come in. A nullable type can represent its normal value range plus null
.
To declare a nullable type, use the ?
symbol after the type. For example:
int? nullableInt = null;
Working with Nullable Types
You can check whether a nullable type has a value using the .HasValue
property and retrieve the value using .Value
. Additionally, the null-coalescing
operator (??
) allows you to assign a default value if the nullable type is null
.
Example: Checking Nullable Types and Using Null-Coalescing Operator
int? nullableInt = null;
if (nullableInt.HasValue)
{
Console.WriteLine("Value: " + nullableInt.Value);
}
else
{
Console.WriteLine("No value");
}
int defaultValue = nullableInt ?? 10; // if nullableInt is null, use 10
Console.WriteLine(defaultValue);
In this example, nullableInt
is checked for a value using .HasValue
, and the null-coalescing
operator provides a default value if nullableInt
is null
.
Nullable Types in Action
Nullable types are particularly useful in scenarios where you interact with external data sources (e.g., databases) that might contain null
values. For example, consider a situation where you fetch an integer value from a database, and the value might be null
.
Example: Nullable Type in Database Interaction
int? fetchedAge = GetAgeFromDatabase(); // might return null
int age = fetchedAge ?? -1; // Use -1 as default if age is null
Console.WriteLine(age);
In this example, the method GetAgeFromDatabase
might return null
if no age is available. The null-coalescing operator ensures that if fetchedAge
is null, -1
is assigned to age
.
Key Points to Remember
- A nullable type is declared using
?
(e.g.,int?
,bool?
). - You can check if a nullable type has a value using
.HasValue
. - Use the null-coalescing operator (
??
) to provide a default value if the nullable type isnull
. - Nullable types are useful when dealing with optional values or values that might be null (e.g., database fields).