Parsing non-existing enum values
A quick question to check the knowledge how enum
values work under the hood.
Giving a simple enum
with int
values
enum MyEnum
{
One = 1,
Two = 2,
Three = 3
}
what outputs the following code?
MyEnum value = (MyEnum)Enum.Parse(typeof(MyEnum), "10");
Console.WriteLine(value);
Surprisingly, the right answer is 10.
I expected that the code throws an exception because we try to parse the value that is not defined. But it is not.
Moreover, even TryParse()
returns true
.
Basically, Enum.Parse()
ignores completely what is defined. It works just like int.Parse()
.
The second surprise for me was that, despite we cast parsed value explicitly to MyEnum
, it still silently works. And no, it doesn’t assign the default value of the MyEnum
or int
. It assigns exactly 10.
The explanation for such strange behavior can be found on the bottom of the official documentation page:
If
value
is the string representation of an integer that does not represent an underlying value of theenumType
enumeration, the method returns an enumeration member whose underlying value isvalue
converted to an integral type.
From my perspective, such behavior is not intuitive. Especially, taking into account that method still throws an exception on parsing named constant strings (e.g. “Ten”).
Just remember to double-check the values additionally using the Enum.IsDefined()
if they come from the user input. Or even better, implement your own version of the Enum.Parse()
with more obvious behavior, and use it everywhere in the projects instead of the standard one.