tags:

views:

107

answers:

2

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.

+6  A: 

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.

Jon Skeet
Wow, I've finally found something that I think is better in Delphi than in C# :)
Peter Morris
A: 

Not entirely true, enums aren't just numbers in .NET and there is validation. I think they have default 0 defined but any other value that is not defined in the enum will cause a compile time error.

So you should always define 0 yourself in an enum. That way you won't be able to set wrong values.

Mule
Wrong answer. An integer other than 0 doesn’t *convert implicitly* to an enum, but it does *explicitly*, i.e. `MyEnum blah = (MyEnum) 47;` works for any enum type.
Timwi
+1, this is excellent advice.
Hans Passant
But when I have a predefined business rule that Monday should equal 1 and Sunday should equal 7, what value should I use for 0?
Peter Morris