C# Tutorial: Nullable Types
Nullable value types, nullable reference types, null-safety operators, and best practices.
Handling null safely
Null is the 'billion dollar mistake'. C# has evolved strong tools to handle null safely.
`int?` makes value types nullable. C# 8 nullable reference types (`string?`) add compile-time null safety for reference types too.
What you'll learn in this C# nullable types tutorial
This interactive C# tutorial has 8 hands-on exercises. Estimated time: 15 minutes.
- Nullable value types — `int?` is shorthand for `Nullable<int>`. It can be null.
- Null coalescing ?? — `??` returns the left side if not null, else the right side.
- Null conditional ?. — `?.` calls a member only if the object is not null, otherwise returns null.
- ??= null coalescing assignment — `??=` assigns the right side only if the left is null.
- Nullable reference types — Enable nullable reference types with `#nullable enable` to get compile-time null safety.
- Null-forgiving operator ! — The `!` postfix operator tells the compiler 'I know this is not null'.
- Pattern matching for null — Use `is null` and `is not null` patterns for readable null checks.
- Null in collections — Collections can contain null values. Use LINQ to filter them.
C# Nullable Types concepts covered
- Handling null safely