Should an Enum start with a 0 or a 1?

前端 未结 14 1405
别那么骄傲
别那么骄傲 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:02

    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.

提交回复
热议问题