Is NULL vs == NULL In C# & .NET
[C#, NET]
If you want to check whether an object is null, there are two popular ways of doing it.
Take the following class:
public sealed class Spy
{
public required string FirstName { get; init; }
public string MiddleName { get; set; }
public required string Surname { get; init; }
}
The first way is this one:
if (spy == null)
Console.WriteLine("The spy is NULL");
else
Console.WriteLine("The spy is NOT NULL");
Here we are using the equality operator, ==
The other way is to use the is null check
if (spy is null)
Console.WriteLine("The spy is NULL");
else
Console.WriteLine("The spy is NOT NULL");
If you want to flip the logic check, negate the experssion using NOT.
if (spy is not null)
For both of this, the response is as follows:

These look interchangeable.
They aren’t!
This is because it is possible to overload the equality operator.
There is nothing stopping anyone from doing this:
public sealed class Spy
{
public required string FirstName { get; init; }
public string MiddleName { get; set; }
public required string Surname { get; init; }
public static bool operator ==(Spy? left, Spy? right)
{
return false;
}
public static bool operator !=(Spy? left, Spy? right)
{
return true;
}
}
Here we have overloaded == and != to return arbitrary values.
Let us now run this code:
if (spy == null)
Console.WriteLine("The spy is NULL");
else
Console.WriteLine("The spy is NOT NULL");
if (spy is null)
Console.WriteLine("The spy is NULL");
else
Console.WriteLine("The spy is NOT NULL");
This prints the following:

We can see our overload has changed the result to NOT NULL, but the is null check returns what we expect.
TLDR
Prefer is null to check whether a value is NULL, to ==
The code is in my GitHub.
Happy hacking