I'm running into a behavior I wasn't expecting when using Enum.TryParse.
If I have an enum:
public enum MyEnum
{
ValueA,
ValueB,
ValueC
}
And then I pass a numeric value (as a string) into Enum.TryParse, like:
MyEnum outputEnum;
bool result = Enum.TryParse("1234", out outputEnum);
Despite the string "1234" not being a possible value, result will come back as true, and my outputEnum will have a value of 1234.
Is there a way I can avoid this sort of behavior? I'm trying to write a function which will process arbitrary string input as an enum, and this has thrown a bit of a monkeywrench in my bad-input detection.
This behavior is by design.
The documentation says:
Call
Enum.IsDefined
to veryify that the value you parsed actually exists in this particularenum
.If you're dealing with
[Flags]
enums (bitmasks), it'll get more complicated.