Imagine I have defined the following Enum:
public enum Status : byte
{
Inactive = 1,
Active = 2,
}
What\'s the best practice to use
Well, I guess I stand in disagreement with most answers that say not to explicitly number them. I always explicitly number them, but that is because in most cases I end up persisting them in a data stream where they are stored as an integer value. If you don't explicitly add the values and then add a new value you can break the serialization and then not be able to accurately load old persisted objects. If you are going to do any type of persistent store of these values then I would highly recommend explicitly setting the values.
Framework Design Guidelines:
✔️ DO provide a value of zero on simple enums.
Consider calling the value something like "None." If such a value is not appropriate for this particular enum, the most common default value for the enum should be assigned the underlying value of zero.
Framework Design Guidelines / Designing Flag Enums:
❌ AVOID using flag enum values of zero unless the value represents "all flags are cleared" and is named appropriately, as prescribed by the next guideline.
✔️ DO name the zero value of flag enums None. For a flag enum, the value must always mean "all flags are cleared."
I like to start my enums at 0, since that's the default, but I also like to include a Unknown value, with a value of -1. This then becomes the default and can help with debugging sometimes.
I'd say best practice is to not number them and let it be implicit - which would start from 0. Since its implicit its the language preference which is always good to follow :)
If not specified numbering starts at 0.
It is important to be explicit since enums are often serialized and stored as an int, not a string.
For any enum stored in the database, we always explicitly number the options to prevent shifting and reassignment during maintenance.
According to Microsoft, the recommended convention is use the first zero option to represent an uninitialized or the most common default value.
Below is a shortcut to start numbering at 1 instead of 0.
public enum Status : byte
{
Inactive = 1,
Active
}
If you wish to set flag values in order to use bit operators on enum values, don't start numbering at the zero value.
First of all, unless you're specifying specific values for a reason (the numeric value has meaning somewhere else, i.e. The Database or external service) then don't specify numeric values at all and let them be explicit.
Second of all, you should always have a zero value item (in non-flags enums). That element will be used as the default value.