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?
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.
equals method uses == operator internally to check if two enum are equal. This means, You can compare Enum using both == and equals method.
We can compare enum variables using the following ways. Using Enum. compareTo() method. compareTo() method compares this enum with the specified object for order.
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.
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.
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?'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With