Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should an Enum start with a 0 or a 1?

Tags:

c#

.net

enums

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
}
like image 415
Acaz Souza Avatar asked Oct 03 '22 02:10

Acaz Souza


People also ask

Do enums always start at 0?

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.

What value do enums start at?

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.

Do Java enums start at 0 or 1?

enum starts always with 0.

Are enums 0 based?

Rule description. The default value of an uninitialized enumeration, just like other value types, is zero.


2 Answers

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."

like image 184
Andrey Taptunov Avatar answered Oct 19 '22 08:10

Andrey Taptunov


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.

like image 72
pstrjds Avatar answered Oct 19 '22 06:10

pstrjds