aevitas
aevitas

Reputation: 3833

Unexpected output when printing enum values

I have some code that takes a ulong parameter, and by using a mapping dictionary, maps that ulong to a value in an enum. However, the enum contains values that are the same for all intents an purposes, so those are re-assigned later on in the enum in a similar fashion as AfricanMango is in the following enum:

public enum Fruits
{
    Banana = 0,
    Strawberry,
    Apple,
    Peach,
    Mango,
    Berry,

    AfricanMango = Mango,

    Cranberry
}

This should tell the compiler to use the same values for both AfricanMango and Mango, whether this implementation actually makes sense from a design point of view is up in the air.

My code was converting the input to an enum value just fine, and when evaluating the result of the function, it returned Fruits.Cranberry. This was the value I was expecting.

However, when subsequently using the result of that function (which the debugger claimed was Fruits.Cranberry), the result suddenly shifted to Fruits.Berry, as can be demonstrated by running the below code:

var fruit = Fruits.Cranberry;

Console.WriteLine(fruit);

One would expect this to output Cranberry, as that is the value it was assigned, but in reality this outputs Berry.

Is this intended behaviour? Do enums get looked up based on the value before them, and is the assignment of AfricanMango messing that up somehow?

Upvotes: 4

Views: 84

Answers (2)

DavidG
DavidG

Reputation: 118937

If you don't specify a value for your enum items, they are created sequentially. So in this case AfricanMango has a value equivalent to Mango which means the values after will be Mango + 1 which maps to Berry.

From the MSDN documentation:

By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1

Upvotes: 6

Patrick Hofman
Patrick Hofman

Reputation: 156948

Yes, the assignment is just incremented. It indeed takes the value of the previous item + 1. See the code from Reflector:

public enum Fruits
{
    AfricanMango = 4,
    Apple = 2,
    Banana = 0,
    Berry = 5,
    Cranberry = 5, // <-- uch
    Mango = 4,
    Peach = 3,
    Strawberry = 1
}

You should put calculated values in the end. In that way the counting won't break, or assign values manually.

From MSDN:

By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1. For example, in the following enumeration, Sat is 0, Sun is 1, Mon is 2, and so forth.

Upvotes: 5

Related Questions