Pattern: Duplicate enum value
Issue: -
Every enum member should either have a unique constant value or be explicitly assigned with a prior member in the enum to indicate explicit intent of sharing value.
This rule helps in catching functional bugs introduced from the following scenarios:
- Accidental typing mistakes, where the user accidentally typed the same constant value for multiple members.
- Copy paste mistakes, where the user copied an existing member definition, then renamed the member but forgot to change the value.
- Merge resolution from multiple branches, where a new member was added with a different name but the same value in different branches.
Example of incorrect code:
enum TestEnum
{
Field1 = 1,
AnotherNameForField1 = Field1, // This is fine
Field2 = 2,
Field3 = 2, // CA1069: This is not fine.
}
Example of correct code:
enum TestEnum
{
Field1 = 1,
AnotherNameForField1 = Field1, // This is fine
Field2 = 2,
Field3 = Field2, // This is also fine
}