Search code examples
c#enums

How to make default incremental value by some constant, in enum


How can I make enum variable's to be incremented in a certain arithmetic progression?

For instance:

enum Days {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};

Now the values will be incremented by 1. How can I increment the values, let’s say by_ 2? Something like:

enum Days {Sat=2, Sun=4, Mon=6, Tue=8, Wed=10, Thu=12, Fri=14};

Do I have to do this manually for each and every element?


Solution

  • Yes, in practice you would have to do it manually -- but do you really need to do so?

    Enums that are not decorated with FlagsAttribute should not need to have specific values assigned to each member because the primary purpose of an enum is to distinguish among a specific set of items, and not necessarily map those items to a specific value. Depending on what you need the numbers for, it is quite possible that using a mapping solution external to the enum would be better software engineering.

    Theoretically you can also use a T4 template to do this programmatically; you would be writing a little code that generates the desired source code automatically from your own viewpoint, but this is overkill for such a simple scenario.