C# - Int value from Enum

To retrieve the integer value associated with an enum in C#, you can use explicit casting or the 'Convert.ChangeType' method. Both approaches allow you to convert an enum value to its underlying integral representation.

Here's an example using explicit casting:


enum DaysOfWeek
{
    Monday = 1,
    Tuesday = 2,
    Wednesday = 3,
    Thursday = 4,
    Friday = 5,
    Saturday = 6,
    Sunday = 7
}

class Program
{
    static void Main()
    {
        DaysOfWeek day = DaysOfWeek.Wednesday;
        int dayValue = (int)day;

        Console.WriteLine(dayValue);  // Output: 3
    }
}

In the above example, we have an enum 'DaysOfWeek' representing the days of the week. We assign the enum value 'DaysOfWeek.Wednesday 'to the variable 'day'. Then, we use '(int)day' to explicitly cast the enum value to an integer. The resulting integer value is stored in the variable 'dayValue', which we then print to the console.

Alternatively, you can use the 'Convert.ChangeType' method to convert an enum value to an integer:



enum DaysOfWeek
{
    Monday = 1,
    Tuesday = 2,
    Wednesday = 3,
    Thursday = 4,
    Friday = 5,
    Saturday = 6,
    Sunday = 7
}

class Program
{
    static void Main()
    {
        DaysOfWeek day = DaysOfWeek.Wednesday;
        int dayValue = (int)Convert.ChangeType(day, typeof(int));

        Console.WriteLine(dayValue);  // Output: 3
    }
}

In this example, we use 'Convert.ChangeType' to convert the 'day' enum value to an integer. We specify 'day as the value to convert and 'typeof(int)' as the target type. The resulting integer value is stored in the 'dayValue' variable and printed to the console.

Both approaches allow you to retrieve the integer value associated with an enum, providing flexibility in working with enum values in numeric form.