Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 890
Peter Morris Avatar asked Sep 21 '10 10:09

Peter Morris


People also ask

Why would you use C?

C is a general-purpose programming language and can efficiently work on enterprise applications, games, graphics, and applications requiring calculations, etc. C language has a rich library which provides a number of built-in functions. It also offers dynamic memory allocation.

Why would I use C++ over C?

C++ is well-rounded in terms of platforms and target applications, so if your project is focused on extremely low-level processing, then you may want to use C++. C++ is often used for large-scale, multi-man, complex projects where separate people need to work on modularised components.

Is C harder than C++?

We can say that C is a hands-on language and we can program it in whichever way we want. C++ consists of some high-level object-oriented programming constructs that help us to code high-level programs. Thus if we say C is easy then C++ is also easier to code.

Why we are still using C language?

The C programming language doesn't seem to have an expiration date. It's closeness to the hardware, great portability and deterministic usage of resources makes it ideal for low level development for such things as operating system kernels and embedded software.


1 Answers

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.

like image 135
Jon Skeet Avatar answered Oct 20 '22 16:10

Jon Skeet