C# how to check for null. (value is null) or (null == value). Can we use `is` operator instead of == operator

Shahid Roofi Khan picture Shahid Roofi Khan · Nov 7, 2018 · Viewed 15.2k times · Source

C# how to check for null. (value is null) or (null == value). Can we use is operator instead of == operator?

C# 7.0 supports const pattern with is operator. So we can use is null for all null checking ?

Can the object be empty as well besides being null?

Answer

Jon Skeet picture Jon Skeet · Nov 7, 2018

Yes, you can use the is operator with the constant pattern of null to check whether a reference (or nullable value type value) is null or not.

Indeed, in C# 7 I would say that using is null is the most idiomatic way of testing for a null value, because it doesn't use any user-defined operators. Consider this:

string x = GetStringFromSomewhere();

if (x == null) { }  // Option 1
if (x is null) { }  // Option 2

Here, option 1 will call the == operator overload defined in string. While that should do what you want (and I expect the JIT compiler will optimize it pretty heavily), it's not like you particularly want to do that - you just want to test whether the value of x is a null reference. That's exactly what option 2 does.

So yes, you can use is null for all null checking if you don't have types that perform odd custom comparisons. It's possible to write a class such that x == null and x is null would give different results, but that would almost always be a design (or implementation) problem.

There's no concept of an object being "empty" - and indeed it's not the object that's null. Leaving nullable value types aside for now, it's a reference that's null, not an object - a null value indicates the absence of an object. It's worth distinguishing carefully between objects and references in your mind.

Some specific object types have a concept of "empty" - for example, a string can be empty, or a collection - but those types have specific ways of testing for emptiness. There's no general concept of an object being empty.