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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With