Imagine I have defined the following Enum:
public enum Status : byte
{
Inactive = 1,
Active = 2,
}
What's the best practice to use enum? Should it start with 1
like the above example or start with 0
(without the explicit values) like this:
public enum Status : byte
{
Inactive,
Active
}
If the first enumerator has no initializer, the value of the corresponding constant is zero. An enumerator-definition without an initializer gives the enumerator the value obtained by increasing the value of the previous enumerator by one. So yes, if you do not specify a start value, it will default to 0.
The default value of Enum constants starts from 0 and increments. It has fixed set of constants and can be traversed easily. However you can still change the start index and customize it with the value of your choice. In the following example, I have set the customized value to be 20 instead of the default 0.
enum starts always with 0.
Rule description. The default value of an uninitialized enumeration, just like other value types, is zero.
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."
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.
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