Should an Enum start with a 0 or a 1?

前端 未结 14 1422
别那么骄傲
别那么骄傲 2020-12-04 10:19

Imagine I have defined the following Enum:

public enum Status : byte
{
    Inactive = 1,
    Active = 2,
}

What\'s the best practice to use

14条回答
  •  执念已碎
    2020-12-04 11:09

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

提交回复
热议问题