I just discovered a subtle bug where I had an enum with two names unintentially sharing the same numeric value (in this case red=10 and crimson=10). I'm a bit surprised this isn't a syntax error.
public enum Colour { Red=10, Blue=11, Green=12, Crimson=10 } // Debug.Write(Colour.Red==Colour.Crimson) outputs True
Is there any real world reason why this behaviour might be a useful or do think it should be a syntax error?
1. Two enum names can have same value. For example, in the following C program both 'Failed' and 'Freezed' have same value 0.
Learn to create Java enum where each enum constant may contain multiple values. We may use any of the values of the enum constant in our application code, and we should be able to get the enum constant from any of the values assigned to it.
The values assigned to the enum names must be integral constant, i.e., it should not be of other types such string, float, etc. All the enum names must be unique in their scope, i.e., if we define two enum having same scope, then these two enums should have different enum names otherwise compiler will throw an error.
Since there is no problem with a type that contains an multiple constants that have the same value, there is no problem with the enum definition. But since the enum does not have unique values you might have an issue when converting into this enum.
public enum Colour { Red=10, Rouge=10, Blue=11, Bleu=11, Green=12, Vert=12, Black=13, Noir=13 }
Beware! If your enum
has multiple elements with the same value, you may get unexpected results when you use Enum.Parse()
. Doing so will arbitrarily return the first element that has the requested value. For example, if you have enum Car { Ford = 1, Chevy = 1, Mazda = 1}
, then (Car)Enum.Parse(typeof(Car), "1")
will return Car.Ford
. While that might be useful (I'm not sure why it would be), in most situations it's probably going to be confusing (especially for engineers maintaining the code) or easily overlooked when problems arise.
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