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.
public class Program { public static void Main(string[] args) { Test a = 0; Console.WriteLine(a); } }
enum Test { a1=0, a2=0, a3=0, a4=0, }
Output:
a2
enum Test { a1=0, a2=0, a3, a4=0, }
Output:
a4
enum Test { a1=0, a2=0, a3, a4, }
Output:
a2
enum Test { a1=0, a2=0, a3, a4 }
Output:
a1
Using Enum. equals() method. equals() method returns true if the specified object is equal to this enum constant.
1. Two enum names can have same value. For example, in the following C program both 'Failed' and 'Freezed' have same value 0.
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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With