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?
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.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
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?
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 treatnull
.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 gettingtrue
every time, sincedt
is non-nullable.