Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected output when printing enum values

Tags:

c#

enums

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?

like image 676
aevitas Avatar asked Dec 19 '22 22:12

aevitas


1 Answers

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

like image 179
DavidG Avatar answered Jan 07 '23 23:01

DavidG