Nullable<T>
A nullable type lets a number like an int hold no value at all, like a form field left blank. It is helpful when the answer is not known yet.
In this page:
Syntax
int? variableName = null; // same as Nullable<int>
variableName.HasValue;
variableName.Value;
int result = variableName ?? defaultValue;
Nullable<T>
Nullable<T> (written as T? for value types) lets a value type like int or bool represent the absence of a value with null, which plain value types can't do otherwise.
Check .HasValue before reading .Value, or use ?? to supply a default. It's commonly used for optional data, like a form field that might be left blank.
Warning:
Reading
.Value on a nullable that is currently null throws an InvalidOperationException.Example: Nullable<T>
using System;
class Program
{
static void Main(string[] args)
{
int? age = null;
Console.WriteLine(age.HasValue);
Console.WriteLine(age ?? -1);
age = 25;
if (age.HasValue)
{
Console.WriteLine(age.Value);
}
}
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Reading
.Valueon aNullable<T>that has no value, which throwsInvalidOperationException; checkHasValue. - Assigning a nullable to a non-nullable without a cast or
.Value. - Forgetting that
nullcompared with<or>gives false.
Chapter Summary
- Generic classes, methods, and interfaces work with many types safely.
- Generic constraints limit which types can be used.
- Covariance and contravariance, and
Nullable<T>, extend how generic types behave.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: