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, known as enumeration members.

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

Defining an enumeration

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

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, the enumeration can start at a value other than 0 and custom values can be assigned to each member.

For example, let’s say 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
}

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

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

Using enumerations

Value Assignment

Once an enumeration is defined, variables of that type can be declared and assigned one of the values defined in the enumeration:

DaysOfTheWeek today = DaysOfTheWeek.Monday;

Value Comparison

These values can also be compared using equality operators:

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

Enumerations Conversion

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

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

Iterating over enumeration values

Sometimes, it can be useful to iterate over the values of an enumeration. To do this, the Enum.GetValues() static method can be used, which returns an array with all the values of the enumeration. Here’s an example:

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

In this example, it iterates over all the values of the MonthsOfYear enumeration and prints each of them to the console.

Practical Examples

Use in a task management application

Suppose we are developing an application to manage tasks and we want to use enumerations to represent the state of a task:

enum TaskStatus
{
    Pending,
    InProgress,
    Completed,
    Cancelled
}

class Task
{
    public string Name { get; set; }
    public TaskStatus Status { get; set; }

    public void ShowStatus()
    {
        Console.WriteLine($"The task '{Name}' is in status: {Status}");
    }
}

class Program
{
    static void Main()
    {
        Task task = new Task
        {
            Name = "Study for the exam",
            Status = TaskStatus.InProgress
        };

        task.ShowStatus(); // Output: The task 'Study for the exam' is in status: InProgress
    }
}

Use in a game

In game development, enumerations can be useful to represent different types of objects or game states:

enum EnemyType
{
    Goblin,
    Orc,
    Dragon
}

class Enemy
{
    public EnemyType Type { get; set; }

    public void ShowType()
    {
        Console.WriteLine($"This enemy is a: {Type}");
    }
}

class Program
{
    static void Main()
    {
        Enemy enemy = new Enemy
        {
            Type = EnemyType.Dragon
        };

        enemy.ShowType(); // Output: This enemy is a: Dragon
    }
}