csharp-enumeraciones

What are and how to use enumerations in C#

  • 4 min

An enumeration is a user-defined value type consisting of a set of named constants (we will call each element a ‘member’ 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.

If you want to learn more, check out the Introduction to Programming Course

Defining an enumeration

To define an enumeration in C#, you use the keyword enum followed by the enumeration name and a block containing the enumeration members:

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

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 enumeration members 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 not starting from 0. We could assign any int to each Enum value like this.

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

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

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

Using enumerations

Value assignment

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

DaysOfTheWeek today = DaysOfTheWeek.Monday;
Copied!

Value comparison

You can also compare these values using equality operators:

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

Converting enumerations

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

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

Iterating over enumeration values

Sometimes, it can 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 with all the values of the enumeration. Here is an example:

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

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

Practical examples