Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

enums

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

I tried the 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 
like image 649
sertsedat Avatar asked May 16 '16 20:05

sertsedat


People also ask

How do you know if two enums are equal?

Using Enum. equals() method. equals() method returns true if the specified object is equal to this enum constant.

Can enums 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.

How do you find the enum constant?

You can use the name() method to get the name of any Enum constants. The string literal used to write enum constants is their name. Similarly, the values() method can be used to get an array of all Enum constants from an Enum type.

What is the default value of enum constant?

The default for one who holds a reference to an enum without setting a value would be null (either automatically in case of a class field, or set by the user explicitly).


1 Answers

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.

like image 85
D Stanley Avatar answered Sep 20 '22 15:09

D Stanley