By default, if no Enum value are assigned, they are automatically assigned by the compiler with a zero-based index:
[Flags]
public enum MyColors
{
Yellow, // 0
Green, // 1
Red, // 2
Blue // 3
}
Assigning binary values to the Enum members allows doing bitwise operations, and they can be assigned by sequencing values in orders of magnitude of 2:
[Flags]
public enum MyColors
{
Yellow = 1,
Green = 2,
Red = 4,
Blue = 8
}
or, more conveniently, make bitwise shifts:
[Flags]
public enum MyColors
{
Yellow = 0,
Green = 0 << 0,
Red = 0 << 1,
Blue = 0 << 2
}
But what if I now want to add Orange to this list between Yellow and Green, while keeping the value numbering nice and consistent? This is the intended result:
[Flags]
public enum MyColors
{
Yellow = 0,
Orange = 0 << 0
Green = 0 << 1,
Red = 0 << 2,
Blue = 0 << 3
}
As you can see, I had to manually edit the shift operations after Orange to keep the numbering nice and consistent. This can quickly become cumbersome with very large Enums. This is not Microsoft Word where you can insert a new item into a numbered list and have the list numbering update automatically after the inserted item. But this kind of feature would be very nice to have.
The problem arises from having to specify the Enum values to binary sequence manually, because by default the Enum members are numbered in decimal.
So, my question is, is it possible to change this default compiler behavior to assign values to Enum members using binary sequence logic, instead of the default decimal one? I am coding with Visual Studio in case that matters.
Disclaimer: I am fully aware that the order of items in Enum doesn't really matter in most cases, nor does the assignment of the member values, meaning I could insert Orange at the bottom and skip having to edit the rest of the member values, or insert Orange where I want, and have a bit messed up numbering sequence. But in certain cases it kind of matters where the newly inserted member is (for example, when printing the Enum member names through reflection), and having the value numbering without any order makes it difficult to determining the value in sequence for a new member. That is why I want to skip having to specify these binary values altogether, and have compiler assign them automatically.