Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum Boxing and Equality

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;
    }
like image 397
Greg Avatar asked Mar 17 '09 00:03

Greg


People also ask

When to use enum in C#?

In C#, an enum (or enumeration type) is used to assign constant names to a group of numeric integer values. It makes constant values more readable, for example, WeekDays. Monday is more readable then number 0 when referring to the day in a week.

What is enum in c sharp?

An enumeration type (or enum type) is a value type defined by a set of named constants of the underlying integral numeric type. To define an enumeration type, use the enum keyword and specify the names of enum members: C# Copy. enum Season { Spring, Summer, Autumn, Winter }

Is enum value type in C#?

Enumeration (or enum) is a value data type in C#. It is mainly used to assign the names or string values to integral constants, that make a program easy to read and maintain.

What is the default value for enum in C#?

The default value for an enum is zero.


1 Answers

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.

like image 72
Jason Kresowaty Avatar answered Oct 18 '22 17:10

Jason Kresowaty