Enumerations

Create and use enums in C#.

Declaration

In addition to primitive data types, it’s possible to create enumerations in C#. An enumeration represents a collection of logically related constants.

For example, we want our method to accept a day of the week as a parameter. We have several options:

  • We could accept a string value (like "Monday")
  • We could accept an integer that represents the day of the week (like 2)
  • We could use enumerations

In our case, we’ll create an enumeration that holds all possible days of the week, so that the user has to choose a constant we provide.

An enumeration is declared using the enum keyword:

enum DayOfWeek 
{
}

The enum keyword is followed by the name of the enumeration. Optionally, we can add the type of the enumeration (it must be of whole number type). If the type is omitted, int is used by default.

enum DayOfWeek : short
{
}

The body of the enumeration consists of comma-separated constants:

enum DayOfWeek : short
{
	Monday,
	Tuesday,
	Wednesday,
	Thursday,
	Friday,
	Saturday,
	Sunday
}

Each element of the enumeration is assigned an integer value, with the first element valued at 0, the second element 1, and so on.

We can specify the elements’ values by indicating the first value:

enum DayOfWeek : short
{
    Monday = 1,
    Tuesday, // 2
    Wednesday, // 3
    Thursday, // 4
    Friday, // 5
    Saturday, // 6
    Sunday // 7
}

We can also specify the values of all constants:

enum YearCount
{
	Year = 1,
	Decade = 10,
	Century = 100,
	Millenium = 1000
}

It’s possible for two constants to have the same underlying value. It’s also possible to assign the value of one constant to another:

enum MusicGenre
{
	Classic = 1,
	Rock = 2,
	Alternative = 2,
	Old = Classic // Old = 1
}

Usage

Each enum defines a new data type. This means that we can declare a variable of this type and use it. Let’s try it out with an example:

Get hands-on with 1200+ tech skills courses.