The Null-Conditional Operator ?.
Read a property, call a method or get an array item from something that may be null with ?. and ?[], which give null instead of stopping the program, and add ?? for a stand-in.
Apprentice · C# · Updated
After this lesson you can
- Read a property, method or array item of something that may be null with ?. and ?[], and give a fallback with ??
Key takeaways
- Reading a property or calling a method on
nullstops the program with aNullReferenceException. captain?.Namereads "if captain isn't null, its Name". Whencaptainisnull, the whole expression isnullinstead of an error.- A
?.result can benull, sonickname?.Lengthis anint?. Add??for a plain value, as innickname?.Length ?? 0. days?[0]reads an array item only when the array isn'tnull. It doesn't check the index: an index past the end still stops the program.
In The Null-Coalescing Operators ?? and ??=, ?? gave a stand-in when a value was missing. But sometimes the missing thing isn't the value you want; it's the object you want to read it from. You want a team captain's name, and the team hasn't chosen a captain. You want the length of a nickname, and there is no nickname. This is behind one of the most common crashes in C# programs, and you'll see its error message often in your first jobs: in a web page that reads a user who isn't signed in, or an order with no delivery address.
Asking nobody for their name
Every team in the basketball league picks a captain at its first practice. Until then, the team's Captain is null. Player? says so, the same way string? says a string may be null; Nullable Reference Types explains that ? fully.
The website's team page prints each captain's name:
Team hawks = new Team("Hawks");
hawks.Captain = new Player("Maya");
Team owls = new Team("Owls"); // no captain chosen yet
Console.WriteLine( quot;Hawks captain: {hawks.Captain.Name}");
Console.WriteLine( quot;Owls captain: {owls.Captain.Name}");
public class Player
{
public string Name { get; }
public Player(string name)
{
Name = name;
}
}
public class Team
{
public string Name { get; }
public Player? Captain { get; set; }
public Team(string name)
{
Name = name;
}
}
Hawks captain: Maya
Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object.
owls.Captain is null: there's no Player object there at all. Asking it for its Name is like walking up to an empty chair and asking it who it is. C# can't answer, so it stops the program with a NullReferenceException: you used a reference (the variable that should lead to an object) that leads to nothing.
Building this code also printed warning CS8602: Dereference of a possibly null reference. for that line. The compiler saw the crash coming. Dereference means following a reference to its object, the . in owls.Captain.Name. The last lesson of this topic shows how to read these warnings and answer them.
The fix you know is an if:
if (owls.Captain != null)
{
Console.WriteLine( quot;Owls captain: {owls.Captain.Name}");
}
else
{
Console.WriteLine("Owls captain: not chosen yet");
}
It works, but it's eight lines for one name, and every place that reads a captain needs its own copy.
?.: only if it's there
Picture a hotel's front desk. You'd like to ask the clerk for a map, but if nobody's at the desk, you don't shout at the empty counter: you walk away with no map. ?. does that. owls.Captain?.Name reads "if the captain isn't null, its name". When the captain is there, you get the name. When it's null, you get null instead of an error. It's called the null-conditional operator.
Add ?? from the last lesson, and the null becomes a stand-in:
Team hawks = new Team("Hawks");
hawks.Captain = new Player("Maya");
Team owls = new Team("Owls");
Console.WriteLine( quot;Hawks captain: {hawks.Captain?.Name}");
Console.WriteLine( quot;Owls captain: {owls.Captain?.Name}");
Console.WriteLine( quot;Owls captain: {owls.Captain?.Name ?? "not chosen yet"}");
public class Player
{
public string Name { get; }
public Player(string name)
{
Name = name;
}
}
public class Team
{
public string Name { get; }
public Player? Captain { get; set; }
public Team(string name)
{
Name = name;
}
}
Hawks captain: Maya
Owls captain:
Owls captain: not chosen yet
The second line shows the null printing as nothing; the third gives it a stand-in. x?.Something ?? fallback is the pair you'll write most: try to read it, and if there's nothing there, use this instead.
When ?. finds null, it skips the rest of the expression and gives null straight away, so nothing after it runs on the empty value.
?. on strings and methods
A string? can be null too, and ?. works on its properties and methods:
string? mayaNickname = "Ace";
string? leoNickname = null;
Console.WriteLine(mayaNickname?.ToUpper());
Console.WriteLine(leoNickname?.ToUpper() ?? "NO NICKNAME");
int mayaLetters = mayaNickname?.Length ?? 0;
int leoLetters = leoNickname?.Length ?? 0;
Console.WriteLine( quot;{mayaLetters} and {leoLetters}");
ACE
NO NICKNAME
3 and 0
Look at the types. Length is an int, but leoNickname?.Length might be null, so it's an int?. That's why the lines above end in ?? 0: without it, the answer can't go in an int.
string? leoNickname = null;
int letters = leoNickname?.Length;
error CS0266: Cannot implicitly convert type 'int?' to 'int'. An explicit conversion exists (are you missing a cast?)
?[]: an array that may be null
The league publishes each team's game days when its schedule is ready. Until then, the team's array of days is null, not an empty array. ?[] reads an item only when the array isn't null:
string[]? hawksDays = { "Saturday", "Sunday" };
string[]? owlsDays = null; // the Owls' schedule isn't out yet
Console.WriteLine(hawksDays?[0] ?? "not scheduled");
Console.WriteLine(owlsDays?[0] ?? "not scheduled");
Console.WriteLine(owlsDays?.Length ?? 0);
Saturday
not scheduled
0
?[] checks only whether the array is null. It doesn't check the index: an index past the end still stops the program, as it did in Array Basics.
string[]? hawksDays = { "Saturday", "Sunday" };
Console.WriteLine(hawksDays?[2]);
Unhandled exception. System.IndexOutOfRangeException: Index was outside the bounds of the array.
Do it: show a team's coach and first game
The league's team cards show two things that may not be there yet: the head coach's phone number, and the team's first game day. A team may have no head coach yet, a coach may not have given a phone number, and a team's schedule may not be out.
The starter has two classes, ready to use:
Coach: aName(astring) and aPhone(astring?,nullwhen the coach hasn't given one).Team: aName(astring), aHeadCoach(aCoach?,nullwhen the team has no coach yet) andGameDays(astring[]?,nullwhen the schedule isn't out).
Each method gets one value:
team: the team, aTeam. It's nevernullitself.
For example, the Hawks:
Team hawks = new Team
{
Name = "Hawks",
HeadCoach = new Coach { Name = "Dana", Phone = "555-0123" },
GameDays = new string[] { "Saturday", "Sunday" }
};
CoachPhone(hawks) returns "555-0123", and FirstGameDay(hawks) returns "Saturday", the first day in the array.
Your job: write two methods.
string CoachPhone(Team team)returns the head coach's phone number. When the team has no head coach, or the coach has no phone number, it returns"call the league office".string FirstGameDay(Team team)returns the first day inGameDays. WhenGameDaysisnull, it returns"not scheduled".
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
A NullReferenceException is what happens when code reads from something that isn't there. ?. and ?[], with ?? behind them, let you say up front what should happen instead.
Key terms
- Null-Conditional Operator
- Null-Coalescing Operator
- NullReferenceException