I often see Simple (non-Flags) Enums declared like this:
enum Something
{
Thingy = 1,
Thangamijig = 2,
Whatsit = 3
}
Why include the optional numeric values? Is this considered a best practice?
The MSDN guidelines for enum design don’t seem to explain a reason for doing this.
A potential answer just ocurred to me: is it to ensure previously serialized objects containing instances of the enum won’t become invalid or have their meaning changed if the enum were to be modified (say by reordering the values or inserting a new value)?
That seems plausible. Are there other reasons?
This is very important if you’re going to save these values externally, like a database, and want to map their value back to code.
If not assigned explicitly, they will be set sequentially at compile time.
For instance:
So
Thingy == 0,Thanamijig == 1,Whatsit == 2This enum is used and saved to the database for a period of time and then some other developer finds a new use for
Somethingand changes it… poorly:Now
Thingy == 1,Thanamijig == 2,Whatsit == 3and you no longer have the proper mapping.This is just one case where not explicitly defining what each enum value maps to can cause a large problem.
enum definition on MSDN
The default underlying type of the enumeration elements is int. By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1. For example:
enum Days {Sat, Sun, Mon, Tue, Wed, Thu, Fri};In this enumeration, Sat is 0, Sun is 1, Mon is 2, and so forth. Enumerators can have initializers to override the default values. For example:
enum Days {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};In this enumeration, the sequence of elements is forced to start from 1 instead of 0.