#466 – Explicitly Assigning Only Some Enumerated Values

When defining an enumerated type, you can explicitly assign values to some of the enumerators and let the compiler implicitly assign values to others.

Any enumerated values that you do not explicitly assign a value to will automatically receive a value one greater than the previous value (whether explicitly or implicitly assigned).

For the following enumerated type:

        public enum Moods
            NOMOOD = 0,
            Grouchy = 10,

The Ambivalent enumerator will have a value of 1, Happy will be 2, Elated will be 3, Crabby will be 11 and Irate will be 12.


About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #466 – Explicitly Assigning Only Some Enumerated Values

  1. Alex says:

    Hi Sean,
    Great blog (this and the WPF one too) – I really like the idea of sharing the small tidbits one at a time (as opposed to lengthy tutorial chapters). May be really good for Lunch and Learn sessions at work to bring the more junior developers on board 😉

    Now, regarding the recent series of Enum-related posts…
    While it is perfectly valid to describe all these intricacies of Enum implementation and usage, I’m wondering if you’re planning to add a word of caution. Yes, I did notice that your blog posts concentrate more on the syntax than on the style… But – IMHO – one of the most important qualities of a good code is its being simple, intuitive, easily readable and comprehensible.
    And while – technically – there may be some rare cases that would justify such deviations from the default usage of Enums, I won’t want to see them in a real production code too often. There is certain “hacky” flavour to this. Let’s say, in the ratings example I would rather see a separate definition of Ratings enum, and have some piece of business logic (a Dictionary, maybe?) that would map one enum to the other.
    Hope I managed to explain what I was trying to say so incoherently 😉

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: