You can convert an int value to an enumeration (enum) type using type casting or the
Enum.Parse method. Here's how you can do it:
Type Casting
You can directly cast an int to the enum type if the integer value corresponds to one of the defined enum values.
enum MyEnum {
Value1,
Value2,
Value3
}
class Program {
static void Main(string[] args) {
int intValue = 2;
MyEnum enumValue = (MyEnum)intValue;
Console.WriteLine(enumValue); // Output: Value3
}
}
Enum.Parse Method
If you need to convert an int value to an enum and you're not sure if the integer value corresponds to a valid enum value, you can use the
Enum.Parse method.
enum MyEnum {
Value1,
Value2,
Value3
}
class Program {
static void Main(string[] args) {
int intValue = 2;
MyEnum enumValue = (MyEnum)Enum.Parse(typeof(MyEnum), intValue.ToString());
Console.WriteLine(enumValue); // Output: Value3
}
}
Convert.ChangeType Method
You can also use the Convert.ChangeType method if you prefer.
enum MyEnum {
Value1,
Value2,
Value3
}
class Program {
static void Main(string[] args) {
int intValue = 2;
MyEnum enumValue = (MyEnum)Convert.ChangeType(intValue, typeof(MyEnum));
Console.WriteLine(enumValue); // Output: Value3
}
}
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.
You can convert an int value to an enumeration (enum) type using type casting or the Enum.Parse method.
Here's how you can do it:
Type Casting
You can directly cast an int to the enum type if the integer value corresponds to one of the defined enum values.
Enum.Parse Method
If you need to convert an int value to an enum and you're not sure if the integer value corresponds to a valid enum value, you can use the Enum.Parse method.
Convert.ChangeType Method
You can also use the Convert.ChangeType method if you prefer.