16

I found a very intersting thing——Let's say:

 enum Myenum { a, b, c= 0 }
    public class Program
    {
        static void Main(string[] args)
        {
            Myenum ma = Myenum.a;
            Console.WriteLine(ma);
        }
    }

The result is a, why?

And if I say:

 enum Myenum { a, b=0, c}
    public class Program
    {
        static void Main(string[] args)
        {
            Myenum ma = Myenum.a;
            Console.WriteLine(ma);
        }
    }

The result becomes "b", why?

xqMogvKW
  • 628
  • 7
  • 17
  • 2
    Related: http://stackoverflow.com/questions/8043027/non-unique-enum-values and http://stackoverflow.com/questions/10268250/enum-tostring-return-wrong-value – Tim Schmelter Sep 26 '14 at 09:12
  • 4
    @TimSchmelter Why would you find duplicates and then post an answer anyway? – Rawling Sep 26 '14 at 09:35
  • 6
    @Rawling: because i thought that they were just related(at least the first link is not a duplicate). I also found the documentation which was not mentioned in the answers. – Tim Schmelter Sep 26 '14 at 09:41
  • 1
    @TimSchmelter In that case, why did you propose it as a duplicate? – dtsg Sep 26 '14 at 14:42

1 Answers1

13

From Enum.ToString:

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. For example, the following enumeration defines two members, Shade.Gray and Shade.Grey, that have the same underlying value.

Related: enum.ToString return wrong value?

So i would assign unique values if you wannt to rely on the name:

enum Myenum { hello = 1, world = 2, qiang = 3 }
Community
  • 1
  • 1
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • 7
    @ths: yes, but you have to know that `Console.WriteLine(ma)` uses `Enum.ToString` and you have to know that this is documented there which is unfortunately often not the case. If it was so simple i wonder why the related (or even duplicate) questions' answers didn't mention MSDN. – Tim Schmelter Sep 26 '14 at 12:12