Skip to content

CSharp Nullability Basics

Joe Care edited this page Dec 22, 2025 · 1 revision

C# Nullability: Basic Null Checks and Operators

This lesson introduces nullable value and reference types, and how to handle null safely.

Related wiki pages:

  • Exceptions and robustness: CSharp-Exceptions-TryCatch.md
  • Properties and initialization: Lessons.md (to be renamed to a properties-focused file)

Official docs:


1. Nullable value types

int? maybeValue = null; // nullable int

if (maybeValue.HasValue)
{
    Console.WriteLine(maybeValue.Value);
}
else
{
    Console.WriteLine("No value");
}

int? is shorthand for Nullable<int>.


2. Basic null check

public static void PrintIfNotNull(string? input)
{
    if (input != null)
    {
        Console.WriteLine($"Input: {input}");
    }
    else
    {
        Console.WriteLine("Input is null.");
    }
}

3. Null-conditional and null-coalescing operators

string? text = null;

int? length = text?.Length;           // null if text is null
int lengthOrZero = text?.Length ?? 0; // 0 if text is null

string result = text ?? "default";   // "default" if text is null
  • ?. stops evaluation if the left side is null.
  • ?? provides a fallback value if the left side is null.

4. Good practices

  • Avoid dereferencing possibly-null values without checks.
  • Enable nullable annotations in your project (<Nullable>enable</Nullable> in the project file) for better compiler warnings.
  • Combine null checks with exception handling where appropriate (CSharp-Exceptions-TryCatch.md).

5. Next steps

  • Apply these operators in your own classes and property accessors.
  • Explore advanced patterns like ArgumentNullException.ThrowIfNull in .NET 6+.

Clone this wiki locally