c# · level 2 · unit 7 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
?. and ?? keep you safe when nothing is there.
A variable for an object can hold null, meaning no object at all, like an empty parking space. Console.ReadLine() gives null when nothing is left to read. Use a member of null, like found.Name, and the program stops with a .
The ?. checks first: found?.Name gives the name if there is a pet, and null if there is not, with no crash. The ?? swaps in a fallback: typed ?? "stranger" gives typed unless it is null.
Together they read well: found?.Name ?? "no pet".
using System;
Pet found = null;
Console.WriteLine(found?.Name ?? "no pet");
found = new Pet("Rex");
Console.WriteLine(found?.Name ?? "no pet");
string typed = null;
Console.WriteLine($"Hello, {typed ?? "stranger"}");
class Pet
{
public string Name { get; set; }
public Pet(string name) { Name = name; }
} Numbers like int can never be null, so these marks are for objects and strings.
guess first
One answer is missing. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
using System;
string[] answers = { " yes ", null };
foreach (string a in answers)
{
Console.WriteLine($"[{a?.Trim() ?? "none"}]");
}
your turn
Your turn. Cope with no answer at all.
This time Gwecode types nothing, so ReadLine gives null. On line 4, use ?. so Trim is skipped for null, and ?? to fall back to empty text. Press run.
output
press run to see what happens
fix it
An empty seat crashes the guest list. Fix it!
output
press run to see what happens
- C# stops with
NullReferenceExceptionon line 6, after AMA. What isgthe second time round? - The second guest is
null, andnullhas noToUpper. Check first, then fall back. - Change line 6 to
Console.WriteLine(g?.ToUpper() ?? "(empty seat)");, then press run.
nailed it
nothing can catch you out now. :D
nullmeans no object at all.?.uses a member only when something is there.??swaps in a fallback fornull.
new words in your collection
- NullReferenceException
- null-conditional operator
- null-coalescing operator
This lesson isn’t saved. A free account remembers every lesson you finish.