Is the use of implicit enum fields to represent numeric values a necessarily bad practice?
Here is a use case: I want an easy way to represent hex digits, and since C# enums are based on integers, they seem like a natural match. I don't like a char
or a string
here, because I have to explicitly validate their values. The problem with enums is that digits [0-9]
are not valid field identifiers (with good reason). It occurred to me that I don't need to declare the digits 0-9
, because they are implicitly present.
So, my hex digit enum would look like:
public enum Hex : int {
A = 10,
B = 11,
C = 12,
D = 13,
E = 14,
F = 15
}
So, I could write Tuple<Hex,Hex> r = Tuple.Create(Hex.F,(Hex)1);
, and r.Item1.ToString() + r.Item2.ToString()
would give me "F1". Basically, my question is that if the ToString()
value of the numeric constant is what I want to name the enum field, why is it problematic to omit the declaration entirely?
An alternative representation as an enum could have the fields declared with some prefix, such as:
public enum Hex : int {
_0 = 0,
_1 = 1,
_2 = 2,
_3 = 3,
_4 = 4,
_5 = 5,
_6 = 6,
_7 = 7,
_8 = 8,
_9 = 9,
A = 10,
B = 11,
C = 12,
D = 13,
E = 14,
F = 15
}
The problem is that the above example would give me "F_1" instead of "F1". Obviously, this is easy to fix. I'm wondering if there are additional problems with the implicit approach that I am not considering.
Numeric EnumNumeric enums are number-based enums i.e. they store string values as numbers. Enums are always assigned numeric values when they are stored. The first value always takes the numeric value of 0, while the other values in the enum are incremented by 1.
An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.
When you need a predefined list of values which do represent some kind of numeric or textual data, you should use an enum. You should always use enums when a variable (especially a method parameter) can only take one out of a small set of possible values.
Enum ValuesIf values are not assigned to enum members, then the compiler will assign integer values to each member starting with zero by default. The first member of an enum will be 0, and the value of each successive enum member is increased by 1.
It's bad practice because it's a clever trick that's surprising to the people who read your code. It surprised me that it actually worked, it had me saying wtf. Remember the only valid measurement of code quality:
Clever tricks don't belong in code that's meant to be read and maintained by others. If you want to output a number as hex, convert it to a hex string using the normal String.Format("{0:X}", value)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With