How can I cast int to enum in C#?
How can I cast int to enum in C#?
I completed my post-graduation in 2013 in the engineering field. Engineering is the application of science and math to solve problems. Engineers figure out how things work and find practical uses for scientific discoveries. Scientists and inventors often get the credit for innovations that advance the human condition, but it is engineers who are instrumental in making those innovations available to the world. I love pet animals such as dogs, cats, etc.
Aryan Kumar
13-Jul-2023Sure, here is how you can cast int to enum in C#:
C#
This code first creates an int. The int is assigned the value 1.
The code then casts the int to an enum. The
(Colors)myIntcast operator is used to cast the int to an enum of typeColors.Finally, the code prints the enum to the console.
Here is an explanation of the code:
usingstatement is used to import theSystemnamespace. TheSystemnamespace contains theEnumclass.Enumclass is used to represent enumerations.Colorsenum is an enumeration that represents the colors red, green, and blue.(Colors)myIntcast operator is used to cast the int to an enum of typeColors.Console.WriteLine()method is used to print a string to the console.