Nullable Types in C#: Handling Missing or Undefined Values
Understand and utilize nullable types in C# for robustly handling situations where values might be missing or undefined. This tutorial explains declaring nullable types using both syntaxes (`Nullable
Nullable Types in C#
In C#, nullable types allow a variable to hold either a value of its declared type or a `null` value. This is particularly useful when dealing with data that might be missing or undefined, such as data coming from a database or a web service where a field may not always have a value assigned to it.
Creating Nullable Types
There are two ways to declare a nullable type in C#:
- Using the `System.Nullable
` struct: `Nullable myNullableInt;` - Using the `?` operator: `int? myNullableInt;` (shorthand notation)
Note: You cannot make reference types (like classes) nullable. Only value types (like `int`, `float`, `bool`, etc.) can be nullable.
Example 1: Using `System.Nullable`
using System;
public class NullableExample {
public static void Main(string[] args) {
Nullable<int> a = 10; // a is nullable int
Console.WriteLine(a.Value); // Accesses the value (throws exception if null)
a = null;
if (a.HasValue) {
Console.WriteLine(a.Value);
} else {
Console.WriteLine("a is null.");
}
}
}
Example 2: Using the `?` Operator
This example demonstrates the shorthand syntax for creating nullable types using the `?` operator:
int? x = 10; // x is a nullable int
double? y = null; // y is a nullable double
bool? z = true; // z is a nullable boolean
Checking for Null Values
Use the `HasValue` property to check if a nullable type variable has a value or is null:
if (myNullableInt.HasValue) {
int value = myNullableInt.Value; // Access the value if it's not null
}