Home > Code Generation > Declaring enumeration types and its elements in CodeRush

Declaring enumeration types and its elements in CodeRush

December 14th, 2011

An enumeration type is a special set of related constants, each with an integer value. Enumerations are useful for defining states and sequences, particularly when there is a natural progression through those states. Each constant in the enumeration list can be compared and formatted using either its name or value. For example, assume that you have to define a variable whose value will represent a day of the week. There are only seven meaningful values which that variable will ever store. To define those values, you can use an enumeration type.

CodeRush helps you to declare enumeration types and its values easily and quickly. Type the code as if you already had the resulting enumeration type declared, e.g.:

public ExperienceLevel GetLevel(int score)
{
  switch (score)
  {
    case 1:
      return ExperienceLevel.Novice;
    case 2:
      return ExperienceLevel.Intermediate;
    case 3:
      return ExperienceLevel.Expert;
  }
  return ExperienceLevel.Unknown;
}

However, the ExperienceLevel enumeration is not yet actually declared. Move the editor caret to the ExperienceLevel reference and execute the Declare Enum code provider:

CodeRush Declare Enum preview

The resulting code will look like this:

public enum ExperienceLevel
{
  Unknown,
  Novice,
  Intermediate,
  Expert
}

If you didn’t declare all elements, and are considering adding other, you are able to continue to enter them and then use the Declare Enum Element code provider for each new element you would like to add into the enumeration type declaration:

CodeRush Declare Enum Element preview

Executing the Declare Enum Element will extend the target enumeration type as follows:

public enum ExperienceLevel
{
  Unknown,
  Novice,
  Intermediate,
  Expert,
  Guru
}
—–
Products: CodeRush Pro, CodeRush Xpress
Versions: 11.2 and up
VS IDEs: any
Updated: Dec/15/2011
ID: C143

Similar Posts: