Codiqo

Learn C# · lesson 36 of 61 · about 9 minutes

Nullable Types

Write the bard's song: represent missing values safely with ?, and handle them with ??, ??= and ?.

What you'll learn

  • Know what string? and int? mean
  • Use ??, ??= and ?.
  • Check for null before using a value

The bard's song

A bard writes a ballad about the battle. It names the hero's companion, but there might not be one: Console.ReadLine() gives null when the input has run out, and an empty line means no companion either, so companion is a string? that's set to null for both. The ballad also tells of the best hit, but if no hit landed there isn't one, so bestHit is an int?: bossHits.Count > 0 ? bossHits.Max() : null. ?. and ?? turn the missing values into words without ever crashing.

Maybe a value

null means no value at all. C# makes you say when something might be missing:

  • string? nickname may be null; plain string shouldn't be
  • int? age is an int that may be missing; age.HasValue checks
  • a ?? b: a, or b if a is null
  • x ??= 5: set x only if it's null
  • a?.Length: the length, or null if a is null (no crash)

The compiler warns when you use a maybe-null value without checking, and Codiqo treats those warnings as errors.

Missing values

string? nickname = null;
Console.WriteLine($"Hi, {nickname ?? "friend"}");
Console.WriteLine(nickname?.Length ?? 0);

int? bestTime = null;
Console.WriteLine(bestTime.HasValue);
bestTime ??= 95;
bestTime ??= 80;
Console.WriteLine(bestTime);

nickname = "Pebs";
if (nickname != null) Console.WriteLine(nickname.ToUpper());

Output

Hi, friend
0
False
95
PEBS

Checking for null yourself

Sometimes a missing value needs different words, not just a fallback. Check it with != null, or HasValue for an int?, and inside the check the compiler knows the value is there.

With or without

string? companion = "  Pip ".Trim();
if (companion == "") companion = null;
string company = companion != null ? $" and {companion}" : ", alone";
Console.WriteLine($"Ada{company}");

int? bestHit = null;
Console.WriteLine(bestHit.HasValue ? $"Best: {bestHit.Value}" : "No hits");

Output

Ada and Pip
No hits

Now try it yourself

This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.