3

How does the algorithm work of determining the Enum value in C#?

Main code:

void Main()
{
    Numbers number;
    number = Numbers.Four;

    Console.WriteLine((int) number);
    Console.WriteLine(number);
    Console.WriteLine(Numbers.Four);
}

Example 1

enum Numbers {
    One,
    Two,
    Three,
    Four = 1,
    Five,
    Six
}

Set the value to 1 for Four

As a result of execution it turns out:

1 Four Four

If you decompile, you can see the following:

private enum Numbers
{
    One = 0,
    Two = 1,
    Three = 2,
    Four = 1,
    Five = 2,
    Six = 3
}

Example 2

enum Numbers {
    One,
    Two,
    Three,
    Four = 2,
    Five,
    Six
 }

Set the value to 2 for Four

As a result of execution it turns out:

2 Three Three

If you decompile, you can see the following:

private enum Numbers
{
    One = 0,
    Two = 1,
    Three = 2,
    Four = 2,
    Five = 3,
    Six = 4
}

Why is the last matching value selected in the first example, and the first matching value selected in the second example?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
  • Because it starts numbering again, incrementally, in textual order after the last manually specified value. I'm sure there are questions where this is already answered, but I can't find them right now. – CodeCaster Jan 08 '20 at 14:08
  • 1
    The values must be unique in the enumeration. – Amin Golmahalleh Jan 08 '20 at 14:11
  • 5
    All of your questions are answered in the three linked duplicates. Most particular, the core of your question: when multiple enum members have the same value, the member you get for the given value is [**not defined**](https://docs.microsoft.com/en-us/dotnet/api/system.enum.tostring?redirectedfrom=MSDN&view=netframework-4.8): _"If multiple enumeration members have the same underlying value and you attempt to retrieve the string representation of an enumeration member's name based on its underlying value, your code should not make any assumptions about which name the method will return."_ – CodeCaster Jan 08 '20 at 14:15
  • 1
    pleasesee this link:https://stackoverflow.com/questions/8043027/non-unique-enum-values – Amin Golmahalleh Jan 08 '20 at 14:17

0 Answers0