Bald Bearded Builder
csharp/csharp-null-theres-a-better-way

C# '== null': There's a Better Way!

The Peacock extension color-codes VS Code workspaces to distinguish projects, Live Share sessions, containers, WSL, and remote environments.

Loads from YouTube when you press play

Transcript 1 topic

Use pattern matching null checks

0:00

Here's a quick tip that prevents bugs in your c sharp. Prefer is and is not pattern matching when checking for nulls rather than relying on the equality and inequality operators. Why? Because classes can override your equality and inequality operators, which means your null checking can get hijacked. But pattern matching with is and is not ignores those equality and inequality operators and looks at the real runtime null.

Check out this class where we've overridden the equality and inequality operators to always return true or false appropriately. Yikes. But what happens when we try to console writeline whether those things equal null or is null or is not null? Well, wait a minute. We know it's null, but we got back a false that t is not null for the operators.

That overridden operator has hijacked our null checking. So for null checking, use is and is not pattern matching and save yourself some time in the future going down these overloaded operator rabbit holes.

Sign in to join in. Reading needs nothing.