Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I compare an enum with null? [duplicate]

Tags:

c#

According to Microsoft's documentation, I can compare value types with null, by marking them nullable. This is particularly useful when using null-propagation in nested objects.

However, when comparing specific enums, which I thought were value-types, I can still compare with null, like this:

public class NullColorComparer
{

    public bool CompareNullWithColor()
    {
        // This return false.
        return null == Color.Red;
    }
}

public enum Color
{
    Red,
    Blue
}

Why does this work? Shouldn't compilation fail with a type error?

like image 261
Andreas Christiansen Avatar asked Apr 26 '18 08:04

Andreas Christiansen


People also ask

Can we compare a enum with null?

The enum is casted to a nullable version of it before comparison, so it can and will evaluate. The result is however always the same.

Can == be used on enum?

equals method uses == operator internally to check if two enum are equal. This means, You can compare Enum using both == and equals method.

Can enum variable be compared?

We can compare enum variables using the following ways. Using Enum. compareTo() method. compareTo() method compares this enum with the specified object for order.

Can I use == for enum Java?

Because there is only one instance of each enum constant, it is permissible to use the == operator in place of the equals method when comparing two object references if it is known that at least one of them refers to an enum constant. (The equals method in Enum is a final method that merely invokes super.


2 Answers

The enum is casted to a nullable version of it before comparison, so it can and will evaluate. The result is however always the same.

That is why the compiler warns you:

Warning CS0472 The result of the expression is always 'false' since a value of type 'Color' is never equal to 'null' of type 'Color?'

Although the comparison is useless, the compiler doesn't prevent you to perform it. Just like it doesn't prevent your to make a if(false) { }, which is just as useless.

like image 76
Patrick Hofman Avatar answered Sep 20 '22 04:09

Patrick Hofman


The null side of your comparison is treated as a Nullable<Program.Color> and it will compile, because you can compare a Nullable<WhatEver> to a WhatEver.

It will however, issue a warning:

Warning CS0472 The result of the expression is always 'false' since a value of type 'Program.Color' is never equal to 'null' of type 'Program.Color?'

like image 26
nvoigt Avatar answered Sep 20 '22 04:09

nvoigt