Why is this even possible? Is it a bug?
using System;
public class InvalidEnumParse
{
public enum Number
{
One,
Two,
Three,
Four
}
public static void Main()
{
string input = "761";
Number number = (Number)Enum.Parse(typeof(Number), input);
Console.WriteLine(number); //outputs 761
}
}
That’s just the way enums work in .NET. The enum isn’t a restrictive set of values, it’s really just a set of names for numbers (and a type to collect those names together) – and I agree that’s a pain sometimes.
If you want to test whether a value is really defined in the enum, you can use
Enum.IsDefinedafter parsing it. If you want to do this in a more type-safe manner, you might want to look at my Unconstrained Melody project which contains a bunch of constrained generic methods.