5

I have a simple enum:

public enum MyEnum
{
    [Description("Zero")]
    Zero,
    [Description("A positive number")]
    Positive,
    [Description("Any integer")]
    AnyInteger,
    [Description("A negative number")]
    Negative,
    [Description("Reserved number")]
    Reserved =2
}

However, running the the following code:

MyEnum temp = MyEnum.AnyInteger;

string en = temp.ToString();

sets the en string to Reserved.

Why does it happens?

Is there is some other way to set the string to the used enum string (in this case AnyInteger)?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
sara
  • 3,824
  • 9
  • 43
  • 71

2 Answers2

5

when defining an enum the first value start with 0 and it going up from there unless you define other wise, so in your case it's:

public enum MyEnum
        {
            [Description("Zero")]
            Zero, //0
            [Description("A positive number")]
            Positive, //1
            [Description("Any integer")]
            AnyInteger, //2
            [Description("A negative number")]
            Negative, //3
            [Description("Reserved number")]
            Reserved = 2 // it's 2 again
           }

you can define the same value twice (or more) in a enum. the ToString find a name with the same value:

MyEnum temp=MyEnum.AnyInteger; //temp = 2

string en=temp.ToString(); // return the name of the first name with value 2.

if you insist that "Reserved" should have the value 2, put him in the right place of order. otherwise remove the =2

Roee Gavirel
  • 18,955
  • 12
  • 67
  • 94
4

It happens because you have set reserved to 2. If you want to set values for your enums, you should do all or none.

John Koerner
  • 37,428
  • 8
  • 84
  • 134
  • 1
    that's totally not true. you can have some values sets. and sometimes you need that. A - you can set the first value to X and all other values will automatically be X+1, X+2 ... B - In case most values are irrelevant to you but still you wish to have one value specific. like the reserved here but with a value that wouldn't normally be retched like 9999 or whatever. – Roee Gavirel Apr 22 '12 at 13:50
  • Notice how I didn't say you have to set all or none, I said you should. It was a recommendation, not a mandate. I agree with you that you can do exactly what the sara did in her post, but then you can get bitten with a small bug like this one. – John Koerner Apr 22 '12 at 13:52
  • right... although I still don't think this is something you should avoid. just use with caution. – Roee Gavirel Apr 22 '12 at 13:56