How to convert between enumeration types and numeric types in C#?
In C#, enumerations can be converted to numeric types or vice versa using type casting.
- Convert an enumeration type to a numerical type.
- Define an enum type with three values: Value1, Value2, and Value3. Then convert one of the enum values, Value1, to an integer value.
- Convert numerical data types to enumeration types.
- // Define an enumeration type
enum MyEnum
{
Value1,
Value2,
Value3
}// Convert a numeric type to an enumeration type
int numericValue = 1;
MyEnum enumValue = (MyEnum)numericValue;
It is important to ensure compatibility between the values when converting between enumeration types and numeric types. If the value of the numeric type is not within the defined range of the enumeration type, the conversion may cause an exception. Therefore, it is best to check if the value is valid before conversion, or verify it using the Enum.IsDefined method.