To cast an int to an enum in C#, you can use the cast operator. The cast operator is a pair of round brackets with the type that you want to cast to. For example, the following code casts the integer 5 to the enum
Color.Red:
C#
enum Color { Red, Green, Blue }
Color red = (Color)5;
In this code, the cast operator is used to cast the integer 5 to the enum
Color. The result is the Color.Red enum.
It is important to note that the enum must have an underlying type of int for this to work. If the enum has a different underlying type, such as a
string or a DateTime, you will get an error.
You can also use the Enum.Parse() method to cast an int to an enum. The
Enum.Parse() method takes the enum type and the integer value as its parameters and returns the corresponding enum value. The following code is equivalent to the previous code:
C#
enum Color { Red, Green, Blue }
Color red = Enum.Parse(typeof(Color), 5);
In this code, the Enum.Parse() method is used to cast the integer 5 to the enum
Color. The first parameter is the type of the enum, and the second parameter is the integer value to be converted.
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.
To cast an int to an enum in C#, you can use the
castoperator. The cast operator is a pair of round brackets with the type that you want to cast to. For example, the following code casts the integer 5 to the enumColor.Red:C#
In this code, the
castoperator is used to cast the integer 5 to the enumColor. The result is theColor.Redenum.It is important to note that the enum must have an underlying type of int for this to work. If the enum has a different underlying type, such as a
stringor aDateTime, you will get an error.You can also use the
Enum.Parse()method to cast an int to an enum. TheEnum.Parse()method takes the enum type and the integer value as its parameters and returns the corresponding enum value. The following code is equivalent to the previous code:C#
In this code, the
Enum.Parse()method is used to cast the integer 5 to the enumColor. The first parameter is the type of the enum, and the second parameter is the integer value to be converted.