Reputation: 7470
I'm just wondering why I get this output :
enum MyEnum
{
a=1,
b=2,
c=3,
d=3,
f=d
}
Console.WriteLine(MyEnum.f.ToString());
OUTPUT
c
But in Mono
OUTPUT
f
So why is the output c? not d? How does the compiler choose c? If I change the code like this:
enum MyEnum
{
a=1,
b=2,
c=3,
d=3,
k=3
}
Console.WriteLine(MyEnum.k.ToString());
OUTPUT
c
again!
Another example:
enum MyEnum
{
a=3,
b=3,
c=3,
d=3,
f=d,
}
MessageBox.Show(MyEnum.f.ToString());
OUTPUT
c
Upvotes: 28
Views: 531
Reputation: 548
From MSDN:
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.
See: http://msdn.microsoft.com/en-us/library/a0h36syw.aspx#Y300
Upvotes: 36
Reputation: 1863
The output is c because ToString resolves the index of the enum and prints out the representation at that index. In the first example, d=3, and the third indexed enum value is c. Similarly, when looking for the third index for k, it arrives at c before k, so that is again the output.
Upvotes: 0