Nullable Types in C#
Introduction
Nullable types in C# allow variables to hold null values in addition to their normal range of values. This is particularly useful when dealing with databases or other data sources where a value might be undefined or missing.
Basic Syntax
To declare a nullable type, you use the ? symbol after the value type. Here is the syntax:
int? nullableInt = null;
In this example, nullableInt can hold any integer value or be null.
Checking for Null
You can check if a nullable type has a value using the HasValue property or by comparing it to null.
int? nullableInt = 5; if (nullableInt.HasValue) { Console.WriteLine("Value: " + nullableInt.Value); } else { Console.WriteLine("No value"); }
Value: 5
Null Coalescing Operator
The null coalescing operator ?? provides a way to define a default value when a nullable type is null.
int? nullableInt = null; int nonNullableInt = nullableInt ?? 0; Console.WriteLine(nonNullableInt); // Output: 0
0
Nullable Types with Reference Types
Starting with C# 8.0, reference types can also be marked as nullable using the ? symbol. This helps in avoiding null reference exceptions.
string? nullableString = null; if (nullableString == null) { Console.WriteLine("String is null"); }
String is null
Examples and Use Cases
Here are a few practical examples where nullable types can be useful:
// Example 1: Database retrieval int? age = GetAgeFromDatabase(userId); if (age.HasValue) { Console.WriteLine("User age: " + age.Value); } else { Console.WriteLine("Age not available"); } // Example 2: User input int? userInput = GetUserInput(); int validInput = userInput ?? -1; Console.WriteLine("Input: " + validInput);
User age: 25 Input: -1