Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it okay for an enum to have two different names with the same numeric value?

Tags:

c#

enums

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?

like image 216
AndyM Avatar asked Jun 30 '10 15:06

AndyM


People also ask

Can two enum names have the same value?

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

Can enum have two values?

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.

Can we have enum containing enum with same constant?

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.

Can 2 enums have the same value in C#?

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.


2 Answers

public enum Colour {     Red=10,     Rouge=10,     Blue=11,     Bleu=11,     Green=12,     Vert=12,     Black=13,     Noir=13 } 
like image 177
Robin Day Avatar answered Sep 19 '22 18:09

Robin Day


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.

like image 25
BillBR Avatar answered Sep 18 '22 18:09

BillBR