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(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.

No comments:

Post a Comment

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

Related Posts

What is the Use of isNaN Function in JavaScript? A Comprehensive Explanation for Effective Input Validation

In the world of JavaScript, input validation is a critical aspect of ensuring that user-provided data is processed correctly. One indispensa...