Skip to content
Codewilds

Lesson 32 of 34 · LINQ & Errors

C# Nullable Types and Null Safety

medium20 XP3 min read

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 to null if the left side is null, otherwise accesses the member.
  • ?? (null-coalescing) returns the left side if it is not null, otherwise the right side.
  • ??= assigns the right side only when the variable is currently null.

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 null from FirstOrDefault or a Find method.
  • Overusing ! to silence warnings instead of handling null.
  • int? arithmetic: int? a = null; int? b = a + 1; is null, not 1.

Assignment

Complete the methods in Program:

  1. FindIndex(items, target) returns the index of the first matching item, or null if it is not there.
  2. DisplayName(nickname, fullName) returns the trimmed nickname, or fullName when the nickname is null, empty or only spaces.
  3. TotalLength(words) adds up the lengths of the words in a list that may contain null entries (they count as 0).
  4. AverageOrNull(values) returns the average, or null for an empty list.
  5. Describe(score) returns "no score" for null and "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
Play the 8 free lessons

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 .

Write code ↓
C#+20 XP

Lesson 32 is part of the full course. The first 8 lessons are free.

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
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.