DEV Community

loading...

Discussion on: The perfect non-null test

Collapse
glenn_k_smith profile image
Glenn Smith

Visual Studio 2019 is giving me a odd compiler error when I use the following code:

// contrived code
public void Test(DateTime dt, string message)
{
if (dt != null) // compiles ok
{
// do something
}

if (!(dt == null)) // compiles ok
{
// do something
}

if (!(dt is null)) // error CS0037: Cannot convert null to 'DateTime' because it is a non-nullable value type
{
// do something
}
}

If DateTime is non-nullable, why do the first two if statements compile? Or, if any type in c# is compatible with object, why does the compiler complain?

Collapse
peledzohar profile image
Zohar Peled Author

the fact that a type is non-nullable doesn't prevent you from asking if it equals null. Remember that == (and !=) can be overloaded and this means that you could have a struct with == and != overloads that specially treat null.
The is operator, on the other hand, can't be overloaded - so the compiler can and will issue an error when attempting to check if a non-nullable type is null.

If you add if(dt is object) you should be getting true every time, since dt is non-nullable.