How to cast int to enum in C#

By FoxLearn 12/2/2024 7:37:57 AM   12
In C#, you can cast an integer to an enum by using the Enum.ToObject method or by performing a direct cast if you know the integer corresponds to a valid value of the enum.

How to cast int to enum in C#?

You can directly cast an integer to an enum type using a cast operator.

For example,  Using Direct Cast

enum Status
{
    Pending = 1,
    Approved = 2,
    Rejected = 3
}

int statusCode = 2;
Status status = (Status)statusCode;

In this example, statusCode is cast directly to the Status enum type.

For example, Using Enum.ToObject Method

Status status = (Status)Enum.ToObject(typeof(Status), statusCode);

When you don't know the enum type at compile time, you can use the Enum.ToObject method to convert an integer to an enum value. This method requires you to provide the Type of the enum, which can be obtained dynamically.

In both cases, you must ensure that the integer value corresponds to a valid value in the enum, otherwise you may get unexpected results.

If you're not sure whether the integer is valid, you can first check using Enum.IsDefined:

if (Enum.IsDefined(typeof(Status), statusCode))
{
    Status status = (Status)statusCode;
}
else
{
    // Invalid status code
}

This ensures that the statusCode is a valid value for the Status enum before performing the cast.