How do I cast int to enum in C#?
How do I cast int to enum in C#?
487
17-Aug-2023
Aryan Kumar
18-Aug-2023To 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.