How do I cast an int to an enum in C#?

To cast an integer to an enum in C#, you can use type casting or the Enum.Parse method. Here's how you can do it using both approaches:

Let's assume you have the following enum:

csharp

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

Method 1: Using Type Casting:

You can directly cast an integer to the enum type if the integer value corresponds to one of the enum values. However, you should be cautious and make sure the integer value is within the valid range of the enum.

csharp

int intValue = 2; // Assuming you want to cast 2 to DaysOfWeek enum

DaysOfWeek day = (DaysOfWeek)intValue;
Console.WriteLine(day); // Output: Tuesday

Method 2: Using Enum.Parse:

The Enum.Parse method allows you to parse a string representation of an enum value and convert it to the enum type. You can use it to parse an integer by first converting the integer to a string.

csharp

int intValue = 4; // Assuming you want to cast 4 to DaysOfWeek enum

DaysOfWeek day = (DaysOfWeek)Enum.Parse(typeof(DaysOfWeek), intValue.ToString());
Console.WriteLine(day); // Output: Thursday

Both methods will cast the integer to the corresponding enum value, but the Enum.Parse method provides more flexibility if you're working with integer values in string format or if you want to handle conversion errors more gracefully.

Comments