Nullable<T> / Nullable Types
Nullable<T> (shorthand: T?) makes value types that normally cannot hold null — such as int, bool, and DateTime — nullable.
Syntax
// Declare a nullable int. int? variable = null; Nullable<int> variable = null; // Same as above. // Get the value if it is not null. int value = variable ?? defaultValue; int value = variable.GetValueOrDefault(defaultValue); // Check whether the value is null. bool result = variable.HasValue; // Retrieve the value (throws an exception if null). int value = variable.Value;
Member List
| Member | Description |
|---|---|
| .HasValue | Returns a bool indicating whether a value is set. Returns false if null. |
| .Value | Retrieves the value. Throws an exception if HasValue is false. |
| .GetValueOrDefault() | Returns the value if set, or the type's default value (e.g., 0 for int) if null. |
| .GetValueOrDefault(T val) | Lets you specify the default value to return when the value is null. |
| variable ?? default | The null-coalescing operator — returns the default value when null. |
Sample Code
using System;
// Use int? to handle a nullable integer.
int? score = null;
Console.WriteLine(score.HasValue); // False
Console.WriteLine(score.GetValueOrDefault(-1)); // -1
score = 85;
Console.WriteLine(score.HasValue); // True
Console.WriteLine(score.Value); // 85
Console.WriteLine(score ?? 0); // 85
// You can perform arithmetic directly on nullable types.
int? a = 10;
int? b = null;
int? total = a + b; // If either operand is null, the result is also null.
Console.WriteLine(total.HasValue); // False
// Use DateTime? to represent an unset date.
DateTime? birthDate = null;
if (!birthDate.HasValue) {
Console.WriteLine("Birth date is not set.");
}
birthDate = new DateTime(1990, 4, 1);
Console.WriteLine($"Birth date: {birthDate?.ToString("yyyy/MM/dd")}"); // Use ?. for safe access
// Comparing nullable types.
int? x = 5;
int? y = null;
Console.WriteLine(x > 3); // True
Console.WriteLine(y > 3); // False (comparisons with null always return false)
Console.WriteLine(y == null); // True
Overview
T? (Nullable<T>) is useful for representing database NULL values or the "not entered" state. For example, you can use null for "no answer" in a survey or "not set" in a date field.
To convert a nullable value to a regular value type, either specify an explicit default with ?? 0 or use .GetValueOrDefault(). Calling .Value without checking first throws an InvalidOperationException.
For null-safe access, also see null-coalescing operators ?? / ??=.
If you find any errors or copyright issues, please contact us.