C# 6.0-8.0 Nullable Operators
Use nullable operators to simplify null checks.
So far, we covered that to avoid the NullReferenceException
:
- We should check for
null
before accessing the methods or properties of an object. - We should reject
null
from our methods when they require some parameters.
Let’s look at the new operators C# introduced to simplify our null
checks: ?.
, ??
, and ??=
. These operators don’t prevent us from having null
in the first place, but they help us simplify our work of checking for null
values.
Without nullable operators
Let’s start with an example and refactor it to use these new operators.
Let’s say we want to find one movie from our catalog to follow its director.
Press + to interact
main.cs
NRE.csproj
string name = null;var movie = FindMovie();if (movie == null|| movie.Director == null|| movie.Director.Name == null){name = "Steven Spielberg";}else{name = movie.Director.Name;}Console.WriteLine($"Follow: {name}");static Movie FindMovie(){// Imagine this is a database call that might// or might not return a movievar lordOfTheRings = new Movie("The Lord of the Rings: The Two Towers", 2002, 8.8f){Director = new Director("Peter Jackson", new DateTime(1961, 10, 31))};// To add some randomness and emulate a database call// without resultsvar random = new Random();var bit = random.NextDouble();return (bit >= 0.5) ? null : lordOfTheRings;}record Movie(string Name, int ReleaseYear, float Rating){public Director Director { get; set; }}record Director(string Name, DateTime BirthDate);
Since the result from FindMovie()
might be ...