Imagine I have defined the following Enum:
public enum Status : byte
{
Inactive = 1,
Active = 2,
}
What\'s the best practice to use
Unless you have a specific reason to change it, leave enums with their default values, which begin at zero.
public enum Status : byte
{
Inactive,
Active
}
I would say, it depends on how you use them. For flagging enum it is a good practice to have 0 for None
value, like that:
[Flags]
enum MyEnum
{
None = 0,
Option1 = 1,
Option2 = 2,
Option3 = 4,
All = Option1 | Option2 | Option3,
}
When your enum is likely to be mapped to a database lookup table, I'd start it with 1. It should not matter much for professionally written code, but this improves readability.
In other cases I'd leave it as it is, giving no care whether they start with 0 or 1.
An Enum is a value type and its default value (for example for an Enum field in a class) will be 0 if not initialized explicitly.
Therefore you generally want to have 0 as an defined constant (e.g. Unknown).
In your example, if you want Inactive
to be the default, then it should have the value zero. Otherwise you might want to consider adding a constant Unknown
.
Some people have recommended that you don't explicitly specify values for your constants. Probably good advice in most cases, but there are some cases when you will want to do so:
Flags enums
Enums whose values are used in interop with external systems (e.g. COM).
Unless you have a good reason to use the raw values, you should only ever be using implicit values and referencing them with Status.Active
and Status.Inactive
.
The catch is that you might want to store data in a flat file or DB, or use a flat file or DB that someone else created. If you're making it yourself, make it so the numbering fits what the Enum is used for.
If the data is not yours, of course you're going to want to use whatever the original dev had used as a numbering scheme.
If you're planning on using the Enum as a set of flags, there is a simple convention that's worth following:
enum Example
{
None = 0, // 0
Alpha = 1 << 0, // 1
Beta = 1 << 1, // 2
Gamma = 1 << 2, // 4
Delta = 1 << 3, // 8
Epsilon = 1 << 4, // 16
All = ~0, // -1
AlphaBeta = Alpha | Beta, // 3
}
Values should be powers of two and can be expressed using bit-shift operations. None
, obviously should be 0
, but All
is less obviously -1
. ~0
is the binary negation of 0
and results in a number that has every bit set to 1
, which represents a value of -1. For compound flags (often used for convenience) other values may be merged using the bitwise or operator |
.
If you start at 1, then you can easily get a count of your things.
{
BOX_THING1 = 1,
BOX_THING2 = 2,
BOX_NUM_THING = BOX_THING2
};
If you start at 0, then use the first one as a value for uninitialized things.
{
BOX_NO_THING = 0,
BOX_THING1 = 1,
BOX_THING2 = 2,
BOX_NUM_THING = BOX_THING2
};
I would start a boolean type enum with a 0.
Unless "Inative" means something other than "Inactive" :)
This retains the standard for those.