← Back to C# Course | Chapter 11: Generics | Lesson 6 of 6

Nullable<T>

In this page:

  1. Nullable<T>

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>

markup
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);
        }
    }
}
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.