How to cast int to enum in C#

How to cast int to enum in C#

How to cast int to enum in C#

Enums, short for enumerations, are a distinct data type consisting of a set of named constants called the enumerators. In C#, they make code more readable and manageable by replacing magic numbers with meaningful names.

1 - What is an Enum?

An enum in C# is a value type defined by a set of named constants of the underlying integral numeric type. By default, the underlying type is int, but it can be any other integral type such as byte, sbyte, short, ushort, uint, long, or ulong.

For instance, you might have an enum representing days of the week:

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

In this example, WeekDays is an enumeration that represents the days of the week. By default, the values are assigned starting from 0 for Monday, 1 for Tuesday, and so on.

Consider the following code without enums:

int day = 3;
if (day == 3)
{
    Console.WriteLine("It's Thursday");
}

Using enums, the code becomes more readable:

WeekDays day = WeekDays.Thursday;
if (day == WeekDays.Thursday)
{
    Console.WriteLine("It's Thursday");
}

2 - Cast int to enum in c#

The below example will show how to cast an int to enum in C#.

public enum MyEnum : int
{
    Apple = 1,
    Grapes = 2,
    Bananna = 3
}

static void Main(string[] args)
{
    var e1 = (MyEnum)1; // Apple
    var e2 = (MyEnum)2; // Grapes

    Console.WriteLine("{0} {1}", e1, e2);
    Console.ReadLine();
}
All Comments