How do I cast int to enum in C#?

 To cast an integer to an enum in C#, you can use the `Enum.Parse` method or the `Enum.TryParse` method.

Here's an example of using the `Enum.Parse` method to convert an integer value to an enum:


int intValue = 2;

DaysOfWeek day = (DaysOfWeek)Enum.Parse(typeof(DaysOfWeek), intValue.ToString());

In this example, we have an integer value of 2 that we want to convert to an enum of type `DaysOfWeek`. We first convert the integer value to a string using the `ToString()` method, and then use the `Enum.Parse` method to convert the string to the enum value. The resulting `day` variable will have the value `Wednesday`.

Alternatively, you can use the `Enum.TryParse` method to perform the conversion and avoid throwing an exception if the integer value cannot be converted to the specified enum:


int intValue = 2;

        DaysOfWeek day;


if (Enum.TryParse(intValue.ToString(), out day))






    Console.WriteLine("Invalid enum value.");


In this example, we attempt to parse the integer value using `Enum.TryParse` and output the resulting `day` value if the conversion is successful. If the conversion fails, we output an error message instead.

No comments:

Post a Comment

Please do not enter any spam link in the comment box.

Related Posts

how to use coalesce in PostgreSQL?

To use the `COALESCE` function in PostgreSQL, follow these steps: 1. Start by writing a SELECT statement or any other query where you want t...