Language: EN

csharp-enumeraciones

What are and how to use enumerations in C#

An enumeration is a user-defined value type that consists of a set of named constants (each element will be referred to as ‘members’ of the enumeration).

Each member of the enumeration is a constant that represents a unique integer value, starting from 0 by default and increasing by one for each subsequent member.

Definition of an enumeration

To define an enumeration in C#, the enum keyword is used followed by the name of the enumeration and a block that contains the members of the enumeration:

enum DaysOfTheWeek
{
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday,
    Sunday
}

In this example, DaysOfTheWeek is an enumeration with seven members: Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, and Sunday.

Enumerations with specific values

It is possible to assign specific values to the members of an enumeration instead of using the default values.

This way, you can start the enumeration at a value other than 0 and assign custom values to each member.

For example, suppose we want to enumerate the months, but we don’t want them to start at 0. We could assign any int to each value of the Enum like this.

enum WeekDays
{
    Monday = 1,
    Tuesday = 2,
    Wednesday = 3,
    Thursday = 4,
    Friday = 5,
    Saturday = 6,
    Sunday = 7
}

If the numbers are consecutive, we can number only the first one, and the rest will be consecutive

enum WeekDays
{
    Monday = 1,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday,
    Sunday
}

Using enumerations

Assigning values

Once an enumeration is defined, you can declare variables of that type and assign one of the values defined in the enumeration:

DaysOfTheWeek today = DaysOfTheWeek.Monday;

Comparing values

You can also compare these values using equality operators:

if (today == DaysOfTheWeek.Monday)
{
    Console.WriteLine("Today is Monday.");
}

Conversion of enumerations

Enumerations in C# are based on integer data types, so it is possible to convert between an enumeration and its underlying type, which by default is int.

int numericValue = (int)DaysOfTheWeek.Wednesday;
Console.WriteLine(numericValue); // Output: 2
DaysOfTheWeek day = (DaysOfTheWeek)4;
Console.WriteLine(day); // Output: Friday

Iterating over the values of an enumeration

Sometimes, it may be useful to iterate over the values of an enumeration. To do this, you can use the static method Enum.GetValues() which returns an array of all the values of the enumeration. Below is an example:

foreach (MonthsOfYear month in Enum.GetValues(typeof(MonthsOfYear)))
{
   Console.WriteLine(month);
}

In this example, we iterate over all the values of the enumeration MonthsOfYear and print each of them to the console.

Practical examples