×

c# · level 2 · unit 7 · lesson 1

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.