What would you rather see? 1, 2, 3, or red, green, blue? Enums allow you to give meaningful names to values. Seems simple, right? It is, except for a few things you should be aware of.
This episode explains the following six aspects of enums that you need to be aware of in order to use them properly:
- Can you declare the underlying storage type that will be used? Some languages allow this and some just use an int. And some like early versions of C++ would try to use an int but could use something else if an int wasn’t large enough.
- Can you specify the enum values themselves? There are times when the exact values are important. What if you want different names for the same value? Or maybe you need to interface with some other code that uses specific values and you need to make sure that your code matches.
- What scope do the enum values occupy? This is important to understand so you know how to handle name conflicts if any. Early version of C++ would promote the enum values to the scope that the enum itself is declared in. Actually, C++ still does this but added a new enum class type that keeps the enum values scoped inside the enum.
- Will enum values convert to integers automatically? This is critical to understanding how you can use enums. If you ever want to combine enum values or save them to another type such as an int, then what will the compiler do?
- Can a variable of the enum type hold values not declared in the enum? If you have an enum that defines only red, green, and blue with the values of 1, 2, and 3, then is it possible to have a variable of this type that contains the value 5? You’d have to perform a cast to get the value 5 into the enum but most languages will allow this. You should never assume that just because you’re using an enum that you will know the values it will contain. It’s still wise to check ranges and have default switch statements in place to catch unexpected values.
- Can the enum type be used for flags? The older C++ enum type could support this because of the way it allowed conversion to ints automatically. Because the newer enum class type doesn’t work like this, then flags will be better implemented with another method. Consider using the bitset class. For C#, you can add an attribute called Flags that will let the compiler know you intend to use the enumeration to hold flags.