Nullable<T>
In this page:
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
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: