When are two enums equal in C#?

2019-02-07 03:24发布

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?

7条回答
小情绪 Triste *
2楼-- · 2019-02-07 04:17

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.

查看更多
登录 后发表回答