The Null-Coalescing Operators ?? and ??=

Give a stand-in for a null value with ??, try several values in turn with a ?? b ?? c, and fill in a variable only when it's null with ??=.

Apprentice · C# · Updated

By

After this lesson you can

  • Give a fallback for a null value with ??, including a chain such as a ?? b ?? c
  • Fill in a variable only when it's null with ??=

Key takeaways

  • value ?? fallback gives value when it isn't null, and fallback when it is. Read ?? as "or, if that's null".
  • With a fallback that can't be null, the result can't be either, so points ?? 0 is a plain int.
  • a ?? b ?? c tries each value from the left and gives the first one that isn't null.
  • ?? steps in only for null. A real 0, false or empty string "" is a value, and it stays.
  • x ??= fallback sets x to the fallback only when x is null. It's short for x = x ?? fallback.

In Nullable Value Types, an int? let the basketball league keep "not played yet" apart from 0. But look at what it cost. Every time the website shows a score, totals a season, or prints a player's details, it has to ask "is this null?" and pick a stand-in when it is. Picking a stand-in for a missing value is one of the most common jobs in programming: a default page title, a guest name for a visitor who hasn't signed in, 0 for a game that hasn't been played. C# has an operator made for it.

An if only to pick a stand-in

The league's standings add up points, and a game that hasn't been played counts as 0 toward the total. With what you know so far, choosing "the points, or 0" takes all this:

int? owlsPoints = null;
int shown;
if (owlsPoints != null)
{
    shown = owlsPoints.Value;
}
else
{
    shown = 0;
}
Console.WriteLine(shown);
0

Nine lines to say one thing: use the points, or 0 if there aren't any. Write that a few dozen times across a website and the real work gets lost among the ifs.

??: use this, or that if it's null

Think of a restaurant's specials board. The waiter reads you the special of the day, and if the board is empty, recommends the house pasta. That's the whole idea: a value, and a stand-in for when it's missing.

?? says it in one line. value ?? fallback gives value when it isn't null, and fallback when it is. Read ?? as "or, if that's null". It's called the null-coalescing operator: to coalesce is to come together into one, and two possible values come together into one answer.

Here's the season total again, with ?? doing the checking:

int?[] hawksSeason = { 42, 38, null };
int total = 0;
foreach (int? points in hawksSeason)
{
    total += points ?? 0;
}
Console.WriteLine(quot;Season points: {total}");
Season points: 80

points ?? 0 is a plain int, not an int?. The fallback, 0, can't be null, so the answer can't be either, and you can add it to total with no .Value.

It works on strings too. On the league's sign-up form, a player can leave their position blank, and the form then gives a string? that is null. A string? is a string that might be null, as Console.ReadLine gives back in While Loop; the last lesson of this topic, Nullable Reference Types, explains it fully.

string? mayaPosition = "Guard";
string? leoPosition = null;   // Leo left the position blank

Console.WriteLine(quot;Maya plays {mayaPosition ?? "any position"}");
Console.WriteLine(quot;Leo plays {leoPosition ?? "any position"}");
Maya plays Guard
Leo plays any position

Several choices in a row: a ?? b ?? c

When a game is called off for rain, the league phones every player. It calls the mobile number if the player gave one, otherwise the home number, and if there's neither, the player has to call the league office. ?? can be chained: C# tries each value from the left and gives the first one that isn't null.

Console.WriteLine(CallNumber("555-0142", "555-0199"));
Console.WriteLine(CallNumber(null, "555-0199"));
Console.WriteLine(CallNumber(null, null));

string CallNumber(string? mobile, string? home)
{
    return mobile ?? home ?? "the league office, 555-0100";
}
555-0142
555-0199
the league office, 555-0100

Read mobile ?? home ?? "the league office, 555-0100" as "the mobile, or if that's null the home number, or if that's null too, the league office". Put the value that can't be null last, so there's always an answer.

Only null gets replaced

?? steps in for null and nothing else. A 0, a false or an empty string "" is a real value, and it comes through as it is:

string? nickname = "";
int? points = 0;
Console.WriteLine(quot;[{nickname ?? "Leo"}]");
Console.WriteLine(points ?? 10);
[]
0

That's usually what you want. A team that scored 0 really scored 0, and a player who said false to "Can you play Saturday?" answered. Only a blank, null, needs a stand-in.

??=: fill it in only if it's empty

Sometimes you don't want a stand-in for one line of output; you want to fill in the variable itself, so it's never null again. Before the season starts, every player who isn't on a team yet goes on the waitlist, and players who are on a team stay where they are:

string? mayaTeam = null;
string? leoTeam = "Hawks";

mayaTeam ??= "Waitlist";
leoTeam ??= "Waitlist";

Console.WriteLine(quot;Maya: {mayaTeam}");
Console.WriteLine(quot;Leo: {leoTeam}");
Maya: Waitlist
Leo: Hawks

x ??= fallback is read "x gets fallback if it's null". It's short for x = x ?? fallback, the way total += 5 is short for total = total + 5. It sets the variable only when the variable is null, so Leo keeps the Hawks. Run it twice and nothing more changes: after the first time, the variable isn't null anymore.

Which one to use

You want to Write
Use a stand-in for this one expression, and leave the variable as it is value ?? fallback
Try several values in turn, and take the first that isn't null a ?? b ?? c
Fill in the variable itself, but only if it's null x ??= fallback

Do it: print the back of a jersey

The league prints each player's jersey from the sign-up form. The back of the jersey shows a name, a space and a number. The nickname and the number are optional on the form, so either can be null.

The method gets three values:

  • firstName: the player's first name, a string ("Leo"). It's never null.
  • nickname: the nickname the player asked for, a string? ("Ace"), or null when they left it blank.
  • number: the jersey number the player asked for, an int? (23), or null when they left it blank.

For example, JerseyBack("Leo", null, 23):

Part Value Shown
Name nickname is null, so use firstName Leo
Number number is 23 23

So JerseyBack("Leo", null, 23) returns "Leo 23".

Your job: write the method string JerseyBack(string firstName, string? nickname, int? number).

  • The name is the nickname, or the first name when the nickname is null.
  • The number is the jersey number, or 0 when the number is null.
  • Return the name, one space, and the number: "Leo 23".

Practiced live on the lesson page: write the C# right there and check it.

Check yourself

2 questions to try on the lesson page.

So what

?? and ??= turn "if it's missing, use this instead" from a block of ifs into a few characters, so your code says what it means and every stand-in stands out.

Key terms

Cheat sheets