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?
Using Enum. equals() method. equals() method returns true if the specified object is equal to this enum constant.
Two enum names can have same value. For example, in the following C program both 'Failed' and 'Freezed' have same value 0.
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.
In C programming, an enumeration type (also called enum) is a data type that consists of integral constants.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With