Consider the following C# code:
enum Beer { Bud = 10, Stella = 20, Unknown }
Typically, it's expected that casting an integer outside the range of an enum, like the following, would throw an exception:
int i = 50; var b = (Beer)i;
However, the above code does not throw an exception and instead outputs '50' to the console.
This is due to a design decision in the .NET Framework. An enum is backed by another value type (int, short, byte, etc.), and can therefore have any value that is valid for those value types.
While this behavior can be confusing, it also allows for the creation of "Bit Flag" enums, where binary patterns are used to represent different flag combinations within an enum value. Defining every possible flag combination explicitly would be tedious.
To address the issue of undefined enum values, it's recommended to use utility methods that fail fast, such as:
public static class EnumUtil<T> { public static T DefinedCast(object enumValue) { if (!System.Enum.IsDefined(typeof(T), enumValue)) throw new InvalidCastException(enumValue + " is not a defined value for enum type " + typeof(T).FullName); return (T)enumValue; } }
This method throws an exception if the cast value is not defined for the enum type.
The above is the detailed content of Why Doesn't Casting an Int to an Invalid Enum Value in C# Throw an Exception?. For more information, please follow other related articles on the PHP Chinese website!