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

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:

  1. Nullable<T>
Syntax
csharp
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>

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);
        }
    }
}
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
  1. Reading .Value on a Nullable<T> that has no value, which throws InvalidOperationException; check HasValue.
  2. Assigning a nullable to a non-nullable without a cast or .Value.
  3. Forgetting that null compared 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:

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.