Search⌘ K
AI Features

Checking for Null Values

Explore techniques to safely handle null values in C#, including the use of new operators like is not and the null-coalescing operator. Understand how to prevent NullReferenceExceptions by properly checking parameters and using C# 10 and 11 enhancements for argument validation.

Checking whether a nullable reference type or nullable value type variable currently contains null is important because if we do not, a NullReferenceException can be thrown, which results in an error.

Handling null values

We should check for a null value before using a nullable variable, as shown in the following code:

C#
// check that the variable is not null before using it
if (thisCouldBeNull != null)
{
// access a member of thisCouldBeNull
int length = thisCouldBeNull.Length; // could throw exception
...
}

C# 7 introduced is combined with the ! (not) operator as an alternative to !=, as shown in the ...