19

Why does this return False

    public enum Directions { Up, Down, Left, Right }

    static void Main(string[] args)
    {
        bool matches = IsOneOf(Directions.Right, Directions.Left, Directions.Right);
        Console.WriteLine(matches);
        Console.Read();
    }

    public static bool IsOneOf(Enum self, params Enum[] values)
    {
        foreach (var value in values)
            if (self == value)
                return true;
        return false;
    }

while this returns True?

    public static bool IsOneOf(Enum self, params Enum[] values)
    {
        foreach (var value in values)
            if (self.Equals(value))
                return true;
        return false;
    }
Greg
  • 23,155
  • 11
  • 57
  • 79

2 Answers2

27

Enum does not implement a == equality operator but it does override the Equals method.

Since it does not implement ==, the system performs a reference equality check. Note that System.Enum is a class not a structure. Hence, values such as Directions.Left are boxed. In this particular case, the boxed objects end up being separate objects, hence they fail a reference equality test.

The compiler understands == for concrete Enum types (such as Directions), but the compiler does not do this special processing against the System.Enum type.

Jason Kresowaty
  • 16,105
  • 9
  • 57
  • 84
4

As JB says, boxing. You can see this by changing from Enum to Directions:

public static bool IsOneOf(Directions self, params Directions[] values)
{
    foreach (var value in values)
        if (self == value)
            return true;
    return false;
}

true is returned.

core
  • 32,451
  • 45
  • 138
  • 193