Search code examples
c#comparison-operators

Weird behavior between null values and overloaded equal operator


Possible Duplicate:
C# okay with comparing value types to null

Why value type as DateTime and Decimal whose the equality operator is overloaded can be compared with null value?

I always thought that value types are non-nullables values, but I'm allowed to write the following code:

DateTime dateTime = DateTime();

if(dateTime == null)
    //do something

The compilation doesn't throw an exception, however the comparison is always false.

Thank you in advance.


Solution

  • It's because there's an implicit conversion to DateTime? available from both sides. It's a bit of a corner case which isn't ideal, basically :(

    In some cases it gives a warning, but not for all (so not here, for example).

    For example, using int:

    int x = 5;
    
    if(x == null)
    {
        Console.WriteLine();
    }
    

    You'll get this warning:

    warning CS0472: The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'int?'