Home > Backend Development > C++ > Why Doesn't Casting an Int to an Invalid Enum Value in C# Throw an Exception?

Why Doesn't Casting an Int to an Invalid Enum Value in C# Throw an Exception?

Linda Hamilton
Release: 2025-01-03 04:55:45
Original
189 people have browsed it

Why Doesn't Casting an Int to an Invalid Enum Value in C# Throw an Exception?

Casting Int to Invalid Enum Value Does Not Throw Exception

Consider the following C# code:

enum Beer
{
    Bud = 10,
    Stella = 20,
    Unknown
}
Copy after login

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;
Copy after login

However, the above code does not throw an exception and instead outputs '50' to the console.

The NET Framework Behavior

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.

Implications and Solutions

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;
    }
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template