Null check, operators ?. and ??
Checking for null. Null guard
If we are going to use a variable or parameter that can take a null value — that is, represents a nullable type (whether value type or reference type) — then to avoid a NullReferenceException, we can check for null:
void PrintUpper(string? text)
{
if (text != null)
{
Console.WriteLine(text.ToUpper());
}
}
In this case, if the text parameter is not null, we call the ToUpper() method on the string, which converts its characters to uppercase.
In addition, using the is operator, we can check the value of an object:
object is value
If the object to the left of the is operator has the value to the right, then is returns true; otherwise, it returns false.
For example, checking a parameter/variable for null value:
void PrintUpper(string? text)
{
if (text is null) return;
Console.WriteLine(text.ToUpper());
}
Or, conversely, using is not we can check for the absence of a value:
void PrintUpper(string? text)
{
if (text is not null)
Console.WriteLine(text.ToUpper());
}
We can also check for matching a type whose value we are going to use:
void PrintUpper(string? text)
{
if (text is string)
Console.WriteLine(text.ToUpper());
else
Console.WriteLine("NULL");
}
Such checks are also called null guard or, figuratively speaking, “protection from null.”
The ?? Operator
The ?? operator is called the null-coalescing operator. It is used to set default values for types that can take a null value:
left_operand ?? right_operand
The ?? operator returns the left operand if it is not null. Otherwise, it returns the right operand. The left operand must be able to take null.
Example:
string? text = null; string name = text ?? "Tom"; // equals "Tom" because text is null Console.WriteLine(name); // Tom int? id = 200; int personid = id ?? 1; // equals 200 because id is not null Console.WriteLine(personid); // 200
But we cannot write the following:
int x = 44; int y = x ?? 100; // Error
Here the variable x represents the value type int and cannot take null, so it cannot be used as the left operand in the ?? operation.
We can also use the derived ??= operator:
string? text = null; text ??= "Sam"; // equivalent to // text = text ?? "Sam"; Console.WriteLine(text); // Sam int? id = 100; id ??= 1; // equivalent to // id = id ?? 1; Console.WriteLine(id); // 100
Null-conditional operator
Sometimes, when working with objects that can take a null value, we may encounter an error when we try to access an object, but the object is actually null.
For example, suppose we have the following class system:
class Person
{
public Company? Company { get; set; } // place of work
}
class Company
{
public string? WebSite { get; set; } // company website
}
The Person object represents a person. Its Company property represents the company where the person works. But a person might be unemployed, so the Company property is of type Company?, meaning it can be null.
The Company class, in turn, contains the WebSite property, which represents the company's website. But a company might not have its own website, so this property is of type string?, meaning it can also be null.
Suppose we need to output to the console, in uppercase, the website of the company where the person works (if they work there and if the company has a website). At first glance, we might write the following:
void PrintWebSite(Person? person)
{
if (person != null)
{
if(person.Company != null)
{
if(person.Company.WebSite != null)
{
Console.WriteLine(person.Company.WebSite.ToUpper());
}
}
}
}
class Person
{
public Company? Company { get; set; } // place of work
}
class Company
{
public string? WebSite { get; set; } // company website
}
In the PrintWebSite() method, we accept a Person? object and, to avoid a NullReferenceException, we sequentially check all values for null so that at the end we can call ToUpper() to print the website name in uppercase.
Although this approach works, it results in a multi-level structure for a simple string output. We can shorten it:
void PrintWebSite(Person? person)
{
if (person != null && person.Company != null && person.Company.WebSite != null)
{
Console.WriteLine(person.Company.WebSite.ToUpper());
}
}
This is simpler, but still somewhat lengthy. To make it even simpler, C# has the null-conditional operator ?.:
object?.member
If the object is not null, then the member — field, property, method — is accessed. If the object is null, the member access is not performed.
Applying this operator, we can rewrite the previous example:
void PrintWebSite(Person? person)
{
Console.WriteLine(person?.Company?.WebSite?.ToUpper());
}
Thus, if person is not null, we access its Company property. If Company is not null, we access the WebSite property of the Company object. If WebSite is not null, we call ToUpper().