Why enums are bad for you
One of the “improvements” of the .NET framework over Java is the inclusion of enums. In fact, it was such a big improvement that Sun has included it in JDK 1.5 (sorry: Java 5). I’m not a big fan of enums in .NET, and in this post I’ll explain why.
Enums are not limit to members
One reason, which has been pointed out by others is that enums are not limited to the possible values of its members, but to the possible values of its underlying type. This means that you can do the following:
public enum Colors {
Red,
Green,
Blue
}
...
Colors myColor = (Colors)42;
without some kind of exception being thrown. To make it even weirder: the string representation of myColor is 42, though its Type is Colors.
Enums enforce switch statements
One of the symptoms that your code is ready for refactoring (also known as code smell) is the switch statement. If you use an enum, you must either use a switch or a if-then-else statement. And every time you add one member to the enum, you must add another case in every place you use the enum.
The excellent Refactoring to patterns suggests replacing complex and rigid switch statements using the Command pattern, or the Visitor.
You could also use a simple class hierarchy.
So instead of the code above, I might define an abstract Color class, with three subclasses: RedColor, GreenColor, and BlueColor. It might seem like a bit of overkill, but it solves the above issues perfectly, and is very object oriented too!