C# — How to cast enum to int (en)?

Let’s see how to convert int to enum type in C#, for different versions of .NET Framework and .NET Core.

.NET Framework 2.0 and above:

To convert from int to enum in .NET Framework 2.0 and later, you can use the Enum.ToObject and Enum.IsDefined methods. The first is used to convert an int to an enum, and the second is used to check if an integer is a valid enum value.

Example:

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

int dayAsInt = 3;

if (Enum.IsDefined(typeof(DaysOfTheWeek), dayAsInt))
{
    DaysOfTheWeek dayAsEnum = (DaysOfTheWeek)Enum.ToObject(typeof(DaysOfTheWeek), dayAsInt);
    // Use dayAsEnum here
}
else
{
    // Handle invalid value here
}Code language: JavaScript (javascript)

.NET Framework 1.0 or 1.1:

In these versions of the .NET Framework, the Enum.ToObject and Enum.IsDefined methods are not available. To convert an int type to an enum type, you can use a cast:

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

int dayAsInt = 3;
DaysOfTheWeek dayAsEnum = (DaysOfTheWeek)dayAsInt;

However, keep in mind that if the int value being cast is not a valid value for the enum, an exception will be thrown.

Добавить комментарий Отменить ответ