#109 – Defining and Using Enums

You can define custom enumeration types using the enum keyword.  Enums derive from System.Enum and consist of a list of named constants, which map to integer values.  An instance of the enum takes on the value of one of the constants.

Defining an enum:

 public enum Mood
 {
     Crabby,
     Happy,
     Petulant,
     Elated
 }

Once you’ve defined an enum, you can declare variables of the new enum type and assign values to them.

 Mood myMood = Mood.Elated;

Internally, each constant value in an enum is represented by a single integral value.  By default, the first constant listed has the value of 0 and consecutive constants have values that increment by one.  For example:

 public enum DumbLevels
 {
     Dumb,      // 0
     Dumber,    // 1
     Dumbest    // 2
 }

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

One Response to #109 – Defining and Using Enums

  1. Pingback: #1,025 – Converting between enum Types | 2,000 Things You Should Know About C#

Leave a comment