If I have duplicate values in a C# enum, saying
enum MyE {
value1 = 1,
value2 = 2,
valued = 1
}
What should be the values of the foll
I disagree with other answers statements
... this isn't guaranteed ...
... you cannot rely on that ...
as well as with msdn statement:
... your application code should never depend on the method returning a particular member's name ...
There was an enum in my software
enum Blabla { A = 0, B = 1, C = 2, D = 3 }
at some point A value changes to AA and later AA changes to AAA. To keep backward compatibility I had to do
enum Blabla { A = 0, AA = 0, AAA = 0, B = 1, C = 2, D = 3 }
This allows to deserialize old enum value (made by older versions of software) as AAA.
Then there was a report which prints Blabla setting value. And at some point every customer using new version start telling me what instead of AAA they see AA value. All of them see AA (and no one report seeing A).
What I did? I simply change the order (until result was AAA)
enum Blabla { AAA = 0, A = 0, AA = 0, ...}
and made a test to ensure what Blabla.AAA will be output as AAA. Problem solved?
Looking at sources of Enum.ToString() (or Enum.GetName()), it uses GetEnumName(), which calls Array.BinarySearch() for sorted array of values to find an index of value.
The result of binary search is deterministic: providing it with the same parameters will return same result.
So:
enum format will be changed (e.g. order of definition and order of list of values differs) or Enum.ToString() will be changed, it can happens however, so make sure you have tests for cases where you rely on return value.