Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When are two enums equal in C#?

Tags:

c#

equality

enums

I have created two enums and I know they are not the same but still I think it makes sense they would be equal since their string representation as well as their numeral representation are equal (and even the same...).

In other words : I would like the first test to pass and the second one to fail. In reality however, they both fail. So : when are two enums in C# equal? Or is there anyway to define the equals operator in C#?

Thanks!

    public enum enumA {one, two}

    public enum enumB {one, two}

    [Test]
    public void PreTest()
    {           
    Assert.AreEqual(enumA.one,enumB.one);
    Assert.AreSame(enumA.one, enumB.one);
    }

UPDATE : 1) So the answers so far all compare representations, be it ints or strings. The enum itself is always unequal I gather? No means to define equality for it?

like image 474
Peter Avatar asked Nov 05 '09 21:11

Peter


People also ask

How do you know if two enums are equal?

Using Enum. equals() method. equals() method returns true if the specified object is equal to this enum constant.

Can two enums have the same value in C?

Two enum names can have same value. For example, in the following C program both 'Failed' and 'Freezed' have same value 0.

Can we call == to compare enums?

lang. Enum (see below code) uses == operator to check if two enum are equal. This means, You can compare Enum using both == and equals method.

Are enums constants in C?

In C programming, an enumeration type (also called enum) is a data type that consists of integral constants.


Video Answer


1 Answers

Enums are strongly typed in C#, hence enumA.one != enumB.one. Now, if you were convert each enum to their integer value, they would be equal.

Assert.AreEqual((int)enumA.one, (int)enumB.one);

Also, I'd like to challenge the statement that because they have the same integer or string representation that they should be the same or equals. Given two enumerations NetworkInterface and VehicleType, it would not be logical for C# or the .Net Framework to allow NetworkInterface.None to equal VehicleType.None when compared as enumeration, by either value or string. However, if the developer cast the strongly typed enumeration to an integer or string, there is nothing the language or framework can do to stop the two from being equals.

To further clarify, you cannot override MyEnum.Equals in order to provide a different equality method. .Net enums are not quite the first class citizens they are in later versions of Java, and I wish that C# allowed for richer interactions with Enums.

like image 95
user7116 Avatar answered Nov 01 '22 19:11

user7116