How are ambiguous enum values resolved in C#?

前端 未结 1 336
暖寄归人
暖寄归人 2020-12-30 20:42

I checked the section of the C# language specification regarding enums, but was unable to explain the output for the following code:

enum en {
    a = 1, b =         


        
相关标签:
1条回答
  • 2020-12-30 21:13

    This is specifically documented to be undocumented behaviour.

    There is probably something in the way the code is written that will end up picking the same thing every time but the documentation of Enum.ToString states 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.

    (my emphasis)

    As mentioned in a comment, a different .NET runtime might return different values, but the whole problem with undocumented behaviour is that it is prone to change for no (seemingly) good reason. It could change depending on the weather, the time, the mood of the programmer, or even in a hotfix to the .NET runtime. You cannot rely on undocumented behavior.

    Note that in your example, ToString is exactly what you want to look at since you're printing the value, which will in turn convert it to a string.

    If you try to do a comparison, all the enum values with the same underlying numerical value is equivalent and you cannot tell which one you stored in a variable in the first place.

    In other words, if you do this:

    var x = en.a;
    

    there is no way to afterwards deduce that you wrote en.a and not en.b or en.c as they all compare equal, they all have the same underlying value. Well, short of creating a program that reads its own source.

    0 讨论(0)
提交回复
热议问题