Checking for null

Checking whether a reference type or nullable value type variable currently contains null is important because if you do not, a NullReferenceException can be thrown, causing an error in your code:

// check is myVariable is not null before using it 
if (ICouldBeNull != null) 
   // do something with ICouldBeNull 

If you are trying to get a field or property from a variable that might be null, use the null check operator (?.), as shown in the following code:

string authorName = null;
// if authorName is null, instead of throwing an exception,
// null is returned
int? howManyLetters = authorName?.Length;

Sometimes you want to either assign a variable to a result, or use an alternative value, such as zero, if the variable is ...

Get C# 7.1 and .NET Core 2.0 – Modern Cross-Platform Development - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.