Null-checking in C# with classes with operator overloading

So you decided to go type safe and happen to use non-nullable reference types in C#. Nice! Furter, you use a library, which of course is not designed for this, but it still works, you add extra typechecks for it’s return values. Everything’s fine, you’re happy.

You do notice that it even denotes some properties as optional, e.g. a CustomClass? sits there somewhere. Of course, you check the property for null before you access it, so you write something like res.Prop != null. Not fearing anything, you compile, and end up with this error message for the res.Prop:

Possible null reference argument for parameter ‘left’ in ‘bool CustomClass.operator !=(CustomClass left, CustomClass right)’

Oh, and also one for the null:

Cannot convert null literal to non-nullable reference type.

What? Well, the res.Prop might be null, of course, that’s why we are doing this after all.

As it turns out, CustomClass has a custom comparison operator. This operator, as shown in the first error message, of course requests CustomClass objects, which may not be null (they don’t have the ?, right?).

Well. So you can’t compare the object with null by using !=, as that operator just does not allow null values. Luckily, ever since C# 7.0, C# has the is operator; with C# 9.0 it also has the not pattern for pattern matching. So you can replace the test with a res.Prop is not null, the comparison operator is not called, and everything is fine.

It’s those fine details that make you love a language, no?