using System;
public enum Colors
{
Red,
Green,
Blue
}
public class CastIntToEnum
{
public static void Main(string[] args)
{
// Create an int.
int myInt = 1;
// Cast the int to an enum.
Colors myColor = (Colors)myInt;
// Print the enum.
Console.WriteLine("The enum is {0}.", myColor);
}
}
This code first creates an int. The int is assigned the value 1.
The code then casts the int to an enum. The (Colors)myInt cast operator is used to cast the int to an enum of type
Colors.
Finally, the code prints the enum to the console.
Here is an explanation of the code:
The using statement is used to import the System namespace. The
System namespace contains the Enum class.
The Enum class is used to represent enumerations.
The Colors enum is an enumeration that represents the colors red, green, and blue.
The (Colors)myInt cast operator is used to cast the int to an enum of type
Colors.
The Console.WriteLine() method is used to print a string to the console.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Sure, 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.