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
}
}
Parse<TEnum>(String, Boolean)Converts the string representation of the name or numeric value of one or more enumerated constants specified by TEnum to an equivalent enumerated object. A parameter specifies whether the operation is case-insensitive.
You can assign different values to enum member. A change in the default value of an enum member will automatically assign incremental values to the other members sequentially. You can even assign different values to each member.
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.IsDefined
after 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.
If you have a enum
with [Flags]
attribute, you can have any value combination. For instance:
[Flags]
enum Test
{
A = 1,
B = 2,
C = 4,
D = 8
}
You could to do this:
Test sample = (Test)7;
foreach (Test test in Enum.GetValues(typeof(Test)))
{
Console.WriteLine("Sample does{0} contains {1}",
(sample & test) == test ? "": " not", test);
}
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