Other Ways To Check For NULL In C# & .NET
[C#, .NET]
In our previous post, “Is NULL vs == NULL In C# & .NET”, we looked at two ways to check for NULL, with a recommendation for the preferred technique, is null.
In this post, we will look at other ways to test for the same.
Property Pattern Matching
In this technique, we take use of the property matching support introduced in .NET 8.
It looks like this:
if (spy is not {})
Console.WriteLine("The spy is NULL");
else
Console.WriteLine("The spy is NOT NULL");
Here we are negating the actual expression , spy is {}
It certainly is terser, but at what cost? Is it easier to read and interpret than is null? Probably not.
Reference Equals
The other technique, available in .NET from the very beginning, is the static Object.ReferenceEqual method.
if (Object.ReferenceEquals(spy, null))
Console.WriteLine("The spy is NULL");
else
Console.WriteLine("The spy is NOT NULL");
TLDR
There are two other ways to check for NULL - property pattern matching and the static Object.ReferenceEquals method.