Search code examples
c#enumscastingoperator-overloadingcomparison-operators

Using greater-than/less-than operator on enums without casting?


I accidently wrote

if (myEnum1 < myEnum2)
{
   //do etc.
}

and I got no compiler errors. Shouldn't I have to cast these enums to their underlying types first:

if ((int) myEnum1 < (int) myEnum2))
{
   //do etc.
}

Are these two snippets equivalent? My IDE, Jetbrains Rider, doesn't seem to think so. I can't jump to the < definitions so I assume it's a compiler thang'?


Solution

  • <, >, <=, >=, == and != are all defined for all enum types E:

    bool operator ==(E x, E y);
    bool operator !=(E x, E y);
    bool operator <(E x, E y);
    bool operator >(E x, E y);
    bool operator <=(E x, E y);
    bool operator >=(E x, E y);
    

    This is specified in the language specification.

    Their behaviour is described as follows:

    The result of evaluating x op y, where x and y are expressions of an enumeration type E with an underlying type U, and op is one of the comparison operators, is exactly the same as evaluating ((U)x) op ((U)y). In other words, the enumeration type comparison operators simply compare the underlying integral values of the two operands.

    So your two code snippets would be the same if the enum has an underlying type of int.