How to convert int to enum in C#

You can convert an integer to an enum in C# by casting the int to the enum type. If the integer value isn't defined in the enum, the cast still succeeds but creates an undefined enum value.

Use Enum.IsDefined() to check if an integer corresponds to a valid enum value before casting. Alternatively, Enum.TryParse() provides safe conversion from strings to enums.

Enums are strongly typed and improve code readability compared to magic numbers. They're stored as integers under the hood, making conversion straightforward.

C# Example Code
using System;

public class IntToEnum
{
    // Define an enum
    enum DayOfWeek
    {
        Sunday = 0,
        Monday = 1,
        Tuesday = 2,
        Wednesday = 3,
        Thursday = 4,
        Friday = 5,
        Saturday = 6
    }

    enum Status
    {
        Pending = 1,
        Active = 2,
        Completed = 3,
        Cancelled = 4
    }

    public static void Main(string[] args)
    {
        // Basic int to enum cast
        int dayNumber = 3;
        DayOfWeek day = (DayOfWeek)dayNumber;
        Console.WriteLine($"Day {dayNumber}: {day}");  // Wednesday

        // Convert to enum and use
        int statusCode = 2;
        Status status = (Status)statusCode;
        Console.WriteLine($"Status code {statusCode}: {status}");  // Active

        // Check if value is defined
        int value = 5;
        if (Enum.IsDefined(typeof(DayOfWeek), value))
        {
            DayOfWeek validDay = (DayOfWeek)value;
            Console.WriteLine($"Valid day: {validDay}");  // Friday
        }

        // Invalid value (not defined in enum)
        int invalidValue = 99;
        DayOfWeek undefinedDay = (DayOfWeek)invalidValue;
        Console.WriteLine($"Undefined day value: {undefinedDay}");  // 99 (no error, but invalid)

        // Safe conversion with validation
        int inputValue = 10;
        if (Enum.IsDefined(typeof(Status), inputValue))
        {
            Status safeStatus = (Status)inputValue;
            Console.WriteLine($"Status: {safeStatus}");
        }
        else
        {
            Console.WriteLine($"Value {inputValue} is not a valid Status");
        }

        // Using Enum.ToObject
        object enumObject = Enum.ToObject(typeof(DayOfWeek), 1);
        DayOfWeek monday = (DayOfWeek)enumObject;
        Console.WriteLine($"Using ToObject: {monday}");  // Monday

        // Get all enum values
        Console.WriteLine("\nAll DayOfWeek values:");
        foreach (DayOfWeek d in Enum.GetValues(typeof(DayOfWeek)))
        {
            Console.WriteLine($"  {(int)d}: {d}");
        }

        // Enum to int (reverse)
        DayOfWeek friday = DayOfWeek.Friday;
        int fridayValue = (int)friday;
        Console.WriteLine($"\n{friday} as int: {fridayValue}");
    }
}