Quantcast
Channel: CodeFari
Viewing all articles
Browse latest Browse all 265

How do I cast int to enum in C#?

$
0
0

 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(day);

}

else

{

    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.


Viewing all articles
Browse latest Browse all 265

Trending Articles