jackjop jackjop - 27 days ago 8
C# Question

Which Enum constant will I get if the Enum values are same

Is there a logic to which constant I get if there are more than one enum constant that has the same value?

I tried variations below, but couldn't get a reasonable logic.

Main Method:



public class Program
{
public static void Main(string[] args)
{
Test a = 0;
Console.WriteLine(a);
}
}


First try:



enum Test
{
a1=0,
a2=0,
a3=0,
a4=0,
}


Output:

a2


Second try:



enum Test
{
a1=0,
a2=0,
a3,
a4=0,
}


Output:

a4


Third try:



enum Test
{
a1=0,
a2=0,
a3,
a4,
}


Output:

a2


Fourth try:



enum Test
{
a1=0,
a2=0,
a3,
a4
}


Output:

a1

Answer

The documentation actually addresses this:

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.

(emphasis added)

However, this does not mean that the result is random. What that means it that it's an implementation detail that is subject to change. The implementation could completely change with just a patch, could be different across compilers (MONO, Roslyn, etc.), and be different on different platforms.

If your system is designed that it requires that the reverse-lookup for enums is consistent over time and platforms, then don't use Enum.ToString. Either change your design so it's not dependent on that detail, or write your own method that will be consistent.

So you should not write code that depends on that implementation, or you are taking a risk that it will change without your knowledge in a future release.