Lesson 32 of 34 · LINQ & Errors
C# Nullable Types and Null Safety
The inventor of the null reference called it his "billion-dollar mistake": a variable that should point to an object but points to nothing, crashing the program the moment you use it. Modern C# gives you the tools to make "no value" explicit and to handle it safely — the compiler even warns you before it goes wrong.
null and NullReferenceException
Reference types (classes, strings, lists) can hold null, meaning no object. Using a member of null throws:
string? name = null;
Console.WriteLine(name.Length); // 💥 NullReferenceException
Nullable value types: int?
Value types like int, double and bool can never be null — an int is always some number. When "no value" is a legitimate state (a score not yet recorded, an unknown age), use the nullable value type int?:
int? bestTime = null;
Console.WriteLine(bestTime.HasValue); // False
bestTime = 42;
Console.WriteLine(bestTime.Value); // 42
Console.WriteLine(bestTime.GetValueOrDefault()); // 42 (0 if null)
int? is a great return type for "find" methods: null clearly means not found, which is better than a magic -1.
Nullable reference types: string?
In modern C# projects (including this course), nullable reference types are enabled. string means "never null" and string? means "might be null". The compiler tracks which variables might be null and warns you when you use them without checking:
string? nickname = GetNickname();
Console.WriteLine(nickname.Length); // warning CS8602: possible null reference
if (nickname is not null)
{
Console.WriteLine(nickname.Length); // fine: the compiler knows it is not null here
}
The warnings do not stop your program from running, but treat them seriously — each one is a possible crash.
The null operators
string? title = null;
int? length = title?.Length; // ?. → null instead of a crash
string shown = title ?? "Untitled"; // ?? → fallback when null
title ??= "Default"; // ??= → assign only if null
int safeLength = title?.Length ?? 0; // combine them
?.(null-conditional) evaluates tonullif the left side isnull, otherwise accesses the member.??(null-coalescing) returns the left side if it is notnull, otherwise the right side.??=assigns the right side only when the variable is currentlynull.
Test for null with x is null / x is not null. The null-forgiving operator x! tells the compiler "trust me, this is not null" — use it rarely, because if you are wrong, it crashes anyway.
Null in LINQ and collections
Several LINQ methods return a default value when nothing matches: FirstOrDefault() gives null for reference types. With int? you can make "no result" explicit, for example Average over an empty list throws, so a method can return null instead.
Common mistakes
- Assuming a lookup succeeded: always handle the
nullfromFirstOrDefaultor aFindmethod. - Overusing
!to silence warnings instead of handling null. int?arithmetic:int? a = null; int? b = a + 1;isnull, not 1.
Assignment
Complete the methods in Program:
FindIndex(items, target)returns the index of the first matching item, ornullif it is not there.DisplayName(nickname, fullName)returns the trimmed nickname, orfullNamewhen the nickname isnull, empty or only spaces.TotalLength(words)adds up the lengths of the words in a list that may containnullentries (they count as 0).AverageOrNull(values)returns the average, ornullfor an empty list.Describe(score)returns"no score"fornulland"score 85"otherwise.
Premium lesson
Unlock the full Learn C# course
- All 34 lessons, bosses and quizzes — lifetime access
- One payment of $35, no subscription
- Finish within 30 days and claim $10.50 (30%) back
Want more than one course?
The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.
Keep learning
Need a quick reminder? The C# cheat sheet has every topic of Learn C# on one page.
Lesson last updated on .