class Program { static void Main(string[] args) { String value = 'Two'; Type enumType = typeof(Numbers); Numbers number = (Numbers)Enum.Parse(enumType, value); Console.WriteLine(Enum.Parse(enumType, value)); } public enum Numbers : int { One, Two, Three, Four, FirstValue = 1 } }
This is a simplified version of an enum I use in an application. The reason to why some of the enum names doesn’t have a value is because I do Enum.Parse with their names as argument, while the ones with a value is parsed from an int.
If you would step through the code above and investigate the ‘number’ variable, you would see that it in fact is ‘Two’, but the output in console is ‘FirstValue’. At this point I can’t see why, do you?
Okay, the solution is simple – just give the valueless enums a value. But I’m still curious.
I suspect that both
FirstValueandTwohave an internal value of 1, so the system doesn’t know which string to output.There is a unique integer value for every enum value, but there is not a unique enum value for every integer value.
When you parse
'two', it gets stored internally as the integer1. Then when you try and convert it back to a string, depending on the technique used to lookup that name, you could get either'Two'or'FirstValue'. As you stated, the solution is to give every enum value a defined integer value.