2008-10-14 by tamberg
|
Avoiding C# EnumsWhile the designers of C# introduced them with good intentions, enums also add a surprising amount of complexity to the language. And some serious sources of errors. The C# Specification states that:
But in a system with more than one assembly, there is not necessarily a single time of compilation. As a result, modifying a public enum can break client assemblies. Consider the following example:
Running the program
Note that this approach is no less type-safe than an enum would be, as it is always possible to assign arbitrary values to an enum variable using a typecast. Even the self-documenting nature of enums can be preserved, with the following pattern:
Such an approach is slightly less concise than an enum, but it eliminates the class of errors described above. Those still unconvinced might want to read the plethora of caveats, dos and don'ts regarding enum design at Krzysztof Cwalina's blog. |