Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding enum in the middle

Tags:

c#

enums

I stumbled upon a code where my colleague has recently modified an existing enum and added another enum just before the last enum, I am guessing he may have done this because the last enum was None(we are not in the same timezone to discuss).

My worry is if any code in the solution tries to fetch the integer value of None Enum(which I couldn't find anywhere luckily, but what about some code tries to do in future), then this will potentially produce wrong results.

Wouldn't it be safe to?

  1. Either Add Enum in the last
  2. Or associate an integer value against each enum so that ordering issue can be resolved?

Please throw some light.

Update: In one of the SO question, I read @Marc Gravell mentioning that inserting in the middle is dangerous, did I understand him correctly? Please see https://stackoverflow.com/a/12716043/2719527

like image 503
Vivek Shukla Avatar asked Apr 26 '18 20:04

Vivek Shukla


People also ask

Can we add constants to enum without breaking existing code?

4) Adding new constants on Enum in Java is easy and you can add new constants without breaking the existing code.

Can you add to enum?

To add functionality to an enumeration type, create an extension method. The default value of an enumeration type E is the value produced by expression (E)0 , even if zero doesn't have the corresponding enum member.

Can we have an enum within an enum?

yes, but you need to know that. no way to easily iterate through all of the enum instances.

Do enums have to be sequential?

It is not necessary to assign sequential values to Enum members. They can have any values. In the above example, we declared an enum PrintMedia .


1 Answers

There is no problem with adding new values at any place in enum list, because when the code with new enum in place is recompiled, the compiler figures out proper ordinals for all values.

There would be a problem if instances of the old enum were persisted, say, to a database. In this case assigning values explicitly would be a better alternative, because stored values would not be changed by a recompile, and would translate to incorrect values on retrieval.

like image 73
Sergey Kalinichenko Avatar answered Sep 22 '22 12:09

Sergey Kalinichenko