Nullable Reference Types
Mark the strings, arrays and objects that may be null as string? or Player?, read the compiler's null warnings as crashes it sees coming, and answer each with a null check, a default, ?. or ??, keeping ! for the rare last resort.
Apprentice · C# · Updated
After this lesson you can
- Mark a variable, parameter, property or return type that may be null with ?, as in string? or Player?
- Answer a compiler null warning by checking for null, giving a default, or using ?. and ??, keeping ! as a last resort
Key takeaways
- Value types such as
inthold their value; reference types such asstring, arrays and classes hold a reference to an object, and a reference can benull. - With nullable reference types on, as in every new project, plain
stringmeans "never null" andstring?means "may be null". The compiler checks your code against those labels. - A null warning, such as CS8602, is a
NullReferenceExceptionthe compiler sees coming. The program still builds, so read every warning. - Answer a warning by saying what's true (
string?), then checking for null, giving a default with??, or reading it with?.instead of.. - The null-forgiving
!, as inphone!.Length, only hides the warning. It changes nothing when the program runs, so it's a last resort.
For three lessons you've been writing string?, Player? and Coach?, with a promise that this lesson would explain them. There's a second promise, from Auto-Properties and Read-Only Properties: a string property needs a starting value such as = "", "or C# warns that it might be null". This lesson keeps both. Those warnings show up in every C# project you'll open at work, and many teams won't accept code until there are none, so it pays to know what each one is telling you.
A string could always be null
In Nullable Value Types, an int couldn't hold null until you wrote int?. A string is different. The league's sign-up sheet has two lines, and only one is filled in:
string[] signUps = new string[2];
signUps[0] = "Maya";
Console.WriteLine(signUps[0].Length);
Console.WriteLine(signUps[1] == null);
4
True
signUps[1] is a plain string, with no ?, and it holds null. So on a string, the ? can't be what allows null. To see what it does, you need the two kinds of types in C#.
Two kinds of types
- A value type holds its value right in the variable, like a number written on a sticky note.
int,double,decimal,boolandcharare value types. A sticky note always has something written on it, so a value type can't benull.int?is a different type that adds an empty state, as you saw. - A reference type holds a reference: directions to an object stored somewhere else, like a coat-check ticket that leads to your coat on the rack.
string, arrays and every class you write, such asPlayer, are reference types. A ticket can be blank, leading to no coat at all: that'snull. Following a blank ticket is theNullReferenceExceptionfrom The Null-Conditional Operator ?..
So any reference type could always be null. That's why null crashes are so common in C#, and why C# 8 added a way to say which references may be null and which never should be.
string?: a label the compiler checks
That feature is called nullable reference types. It's switched on in every new C# project, and in every file you run with dotnet run. With it on, the compiler reads your types as labels:
stringmeans "this is nevernull".string?means "this may benull, so check before you use it".
The same goes for arrays (string[]?) and your own classes (Player?). Unlike int?, the ? on a reference type isn't a different type. When the program runs, a string and a string? are the very same string. The difference is all at build time: the compiler checks your code against the labels, and warns wherever it could crash.
string nickname = null;
string? phone = null;
Console.WriteLine(nickname);
Console.WriteLine(phone.Length);
It builds, runs, and stops:
Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object.
(The first line printed is empty: that's nickname, which is null.) The compiler saw it coming. Building the program printed two warnings, and then the program ran anyway, because warnings don't stop a build:
warning CS8600: Converting null literal or possible null value to non-nullable type.
warning CS8602: Dereference of a possibly null reference.
The second warning points at phone.Length, the very line that crashed. A null warning is a crash the compiler sees coming. Read every one.
Reading the warnings
Each warning has a number, starting with CS86, and a message. These are the ones you'll meet most:
| Warning | It says | What it means |
|---|---|---|
| CS8600 | Converting null literal or possible null value to non-nullable type. | Something that may be null is going into a plain string (or other "never null" type). |
| CS8602 | Dereference of a possibly null reference. | You're using . on something that may be null. Dereference means following the reference to its object. |
| CS8603 | Possible null reference return. | A method that promises a plain Player may return null. |
| CS8604 | Possible null reference argument for parameter 'name' ... | A value that may be null is being passed to a parameter that says "never null". |
| CS8618 | Non-nullable property 'Phone' must contain a non-null value when exiting constructor. ... | A "never null" property starts out null, because nothing set it. |
Here's a roster search that gets two of them. Searching for a player who isn't there returns null from a method that promised a Player, and a Phone property promises a phone number nobody has set:
Player[] roster = { new Player("Maya"), new Player("Leo") };
Player found = FindPlayer(roster, "Sam");
Console.WriteLine(found.Name);
Player FindPlayer(Player[] roster, string name)
{
foreach (Player player in roster)
{
if (player.Name == name)
{
return player;
}
}
return null;
}
public class Player
{
public string Name { get; }
public string Phone { get; set; }
public Player(string name)
{
Name = name;
}
}
Running it stops at found.Name, because Sam isn't on the roster:
Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object.
Building it gave two warnings first:
warning CS8603: Possible null reference return.
warning CS8618: Non-nullable property 'Phone' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the property as nullable.
Answering a warning
A warning is a question: can this really be null? Answer it honestly.
- If it can be
null, say so with?.FindPlayerreally can find nobody, so its return type isPlayer?. Not every player gives a phone number, soPhoneis astring?. That clears CS8603 and CS8618, and moves the question to the code that uses them, which is where it belongs. - Then handle the
nullwhere the value is used, with what you already know:- Check for null. After
if (maya != null), the compiler knowsmayaisn'tnullinside theif, so it doesn't warn there. - Give a default with
??:maya.Phone ?? "no phone". - Read with
?., and add??for a stand-in:sam?.Name ?? "Sam isn't on the roster".
- Check for null. After
- If it can never be
null, make sure it can't. Give the property a starting value (= ""), or set it in the constructor, asNameis.
Here's the roster search with every warning answered:
Player[] roster = { new Player("Maya"), new Player("Leo") };
roster[0].Phone = "555-0142";
Player? maya = FindPlayer(roster, "Maya");
if (maya != null)
{
Console.WriteLine( quot;{maya.Name}: {maya.Phone ?? "no phone"}");
}
Player? sam = FindPlayer(roster, "Sam");
Console.WriteLine(sam?.Name ?? "Sam isn't on the roster");
Player? FindPlayer(Player[] roster, string name)
{
foreach (Player player in roster)
{
if (player.Name == name)
{
return player;
}
}
return null;
}
public class Player
{
public string Name { get; }
public string? Phone { get; set; }
public Player(string name)
{
Name = name;
}
}
Maya: 555-0142
Sam isn't on the roster
No warnings, and no crash: every place that could meet a null says what to do with it.
The null-forgiving operator !: a last resort
There's one more way to make a warning go away: put ! after the value. phone!.Length tells the compiler "I promise phone isn't null here, don't warn me". It's called the null-forgiving operator. (It's the same symbol as the "not" in !isOpen, but it comes after a value instead of before a condition.)
The catch: ! changes nothing when the program runs. It switches off the warning and nothing else, so if your promise is wrong, the crash still comes:
string? phone = null;
Console.WriteLine(phone!.Length);
Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object.
This code builds with no warning at all, and it still crashes. That's why ! is the last resort: use it only when you know for certain a value isn't null and the compiler can't see why. When you're tempted to type it, reach for a check, ?? or ?. first: they keep you safe when you're wrong, and ! doesn't.
Do it: look a player up on the roster
The league's coaches look players up by name to call them about practice. A name might not be on the roster, and a player might not have given a phone number, so both answers can be missing.
The starter has the class Player, ready to use: a Name (a string) and a Phone (a string?, null when the player hasn't given one).
Each method gets two values:
roster: the players on the team, aPlayer[].name: the name to look for, astring("Maya"). It matches a player'sNameexactly.
For example, with this roster:
Player[] roster =
{
new Player { Name = "Maya", Phone = "555-0142" },
new Player { Name = "Leo" }
};
| Call | Found | Returns |
|---|---|---|
ContactLine(roster, "Maya") |
Maya, phone 555-0142 | "Maya: 555-0142" |
ContactLine(roster, "Leo") |
Leo, no phone | "Leo: no phone" |
ContactLine(roster, "Sam") |
nobody | "Sam: not on the roster" |
Your job: write two methods.
Player? FindPlayer(Player[] roster, string name)returns the player whoseNameisname, ornullwhen nobody on the roster has that name.string ContactLine(Player[] roster, string name)usesFindPlayer, and returns the name, a colon and a space, then:- the player's phone, when the player is found and has one:
"Maya: 555-0142"; no phone, when the player is found but their phone isnull:"Leo: no phone";not on the roster, whenFindPlayerreturnsnull:"Sam: not on the roster".
- the player's phone, when the player is found and has one:
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
The ? on a reference type is how your code says, out loud, where null can turn up, so the compiler can point to every crash before a user finds it.