C#9 provides us with additional pattern combinators such as
or to match expressions.
One of my favourite is the
not pattern. Especially in the following use case. As Developers defensive programming is extremely important and we quite often need to check an object is not null before we perform any operations or use the object itself to prevent exceptions occurring. This is good practice and common in error logging when an object is null unexpectedly.
not logical pattern matching available in C#9 feature code would look something like this, where
financial is an instance of type
Financial and we are checking it is not null before using it.
Example 1 – check to see if an object is not null.
if (financial != null)
Example 2 – Another null check variation, it is slightly more difficult to read and is using the negation operator.
if (!(financial is null))
I personally wasn’t the biggest fan of the syntax in the above examples, but used example 1 when required. I really like this new C#9 feature, and believe it makes the check more readable, allowing our code to express it’s intent clearly, without unnecessary negation or inequality operators.
Example 3 – Checking for null using the not logical pattern in C#9.
if (financial is not null)