How do I cast int to enum in C#?

Post author: Adam VanBuskirk
Adam VanBuskirk
5/13/23 in
Tech
C#

In C#, you can cast an integer value to an enum type using the explicit type cast operator. This allows you to assign an integer value to an enum variable or pass an integer value to a method that expects an enum parameter.

Here’s an example of how to cast an int value to an enum type in C#:

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

class Program
{
    static void Main(string[] args)
    {
        int dayNumber = 3; // Thursday

        // Cast the integer value to the DaysOfWeek enum type
        DaysOfWeek day = (DaysOfWeek)dayNumber;

        Console.WriteLine(day); // Output: Thursday
    }
}

In this example, we define an enum called DaysOfWeek with seven named values. We then define an integer variable dayNumber and assign it the value 3, which corresponds to the Thursday value in the DaysOfWeek enumeration.

To cast the dayNumber value to the DaysOfWeek enum type, we use the explicit type cast operator (DaysOfWeek) and assign the result to an enum variable called day.

Finally, we print the value of day to the console using Console.WriteLine. The output will be Thursday, which is the enum value corresponding to the integer value 3.

It’s important to note that if you try to cast an integer value to an enum type that does not include that value, a runtime exception will be thrown. For example, if you tried to cast the value 10 to the DaysOfWeek enum type, which only has values from 0 to 6, a System.InvalidCastException exception would be thrown.

Sign up today for our weekly newsletter about AI, SEO, and Entrepreneurship

Leave a Reply

Your email address will not be published. Required fields are marked *


Read Next




© 2024 Menyu LLC