Why would C# allow an invalid enum value
I've spent a while trying to understand why my WPF app wasn't databinding to an enum property propertly and this is the cause.
static void Main(string[] args)
{
MyEnum x = 0;
Console.WriteLine(x.ToString());
Console.ReadLine();
}
public enum MyEnum
{
First = 1,
Second = 2开发者_运维问答
}
Essentially the problem was that there was no default value set for the enum property in the constructor of the class I was binding to, so it was defaulting to zero.
Is there someway I can tell the C# compiler that I want it to only accept valid values (and default to the lowest value)? I don't want my property to accept invalid values, and I don't want to have to write setter code for every property that uses an enum.
No, unfortunately not.
C# enums are just named numbers, really - there's no validation at all. I agree it would be very nice to see this, as well as enums with behaviour (like in Java). I haven't heard anything to suggest it's coming any time soon though :(
Note that the default value of a type will always be the value represented by "all zero bits" - there's no way of getting round that within the type system, really. So either you need to make that a sensible default value, or you'd have to explicitly test against it even in a validating system (like testing against null for reference types).
Just to be clear, I believe there are times when it makes sense to have the "names for numbers" kind of type... but I think a genuinely restricted set of values would be even more useful.
精彩评论