Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6058199
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 23, 20262026-05-23T08:34:25+00:00 2026-05-23T08:34:25+00:00

If I have an enum like so: enum Beer { Bud = 10, Stella

  • 0

If I have an enum like so:

enum Beer
{
    Bud = 10,
    Stella = 20,
    Unknown
}

Why does it not throw an exception when casting an int that is outside of these values to a type of Beer?

For example the following code doesn’t throw an exception, it outputs ’50’ to the console:

int i = 50;
var b = (Beer) i;

Console.WriteLine(b.ToString());

I find this strange…can anyone clarify?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-23T08:34:26+00:00Added an answer on May 23, 2026 at 8:34 am

    Taken from Confusion with parsing an Enum

    This was a decision on the part of the people who created .NET. An enum is backed by another value type (int, short, byte, etc), and so it can actually have any value that is valid for those value types.

    I personally am not a fan of the way this works, so I made a series of utility methods:

    /// <summary>
    /// Utility methods for enum values. This static type will fail to initialize 
    /// (throwing a <see cref="TypeInitializationException"/>) if
    /// you try to provide a value that is not an enum.
    /// </summary>
    /// <typeparam name="T">An enum type. </typeparam>
    public static class EnumUtil<T>
        where T : struct, IConvertible // Try to get as much of a static check as we can.
    {
        // The .NET framework doesn't provide a compile-checked
        // way to ensure that a type is an enum, so we have to check when the type
        // is statically invoked.
        static EnumUtil()
        {
            // Throw Exception on static initialization if the given type isn't an enum.
            Require.That(typeof (T).IsEnum, () => typeof(T).FullName + " is not an enum type.");
        }
    
        /// <summary>
        /// In the .NET Framework, objects can be cast to enum values which are not
        /// defined for their type. This method provides a simple fail-fast check
        /// that the enum value is defined, and creates a cast at the same time.
        /// Cast the given value as the given enum type.
        /// Throw an exception if the value is not defined for the given enum type.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="enumValue"></param>
        /// <exception cref="InvalidCastException">
        /// If the given value is not a defined value of the enum type.
        /// </exception>
        /// <returns></returns>
        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;
        }
    
        /// <summary>
        /// 
        /// </summary>
        /// <param name="enumValue"></param>
        /// <returns></returns>
        public static T Parse(string enumValue)
        {
            var parsedValue = (T)System.Enum.Parse(typeof (T), enumValue);
            //Require that the parsed value is defined
            Require.That(parsedValue.IsDefined(), 
                () => new ArgumentException(string.Format("{0} is not a defined value for enum type {1}", 
                    enumValue, typeof(T).FullName)));
            return parsedValue;
        }
    
        public static bool IsDefined(T enumValue)
        {
            return System.Enum.IsDefined(typeof (T), enumValue);
        }
    
    }
    
    
    public static class EnumExtensions
    {
        public static bool IsDefined<T>(this T enumValue)
            where T : struct, IConvertible
        {
            return EnumUtil<T>.IsDefined(enumValue);
        }
    }
    

    This way, I can say:

    if(!sEnum.IsDefined()) throw new Exception(...);
    

    … or:

    EnumUtil<Stooge>.Parse(s); // throws an exception if s is not a defined value.
    

    Edit

    Beyond the explanation given above, you have to realize that the .NET version of Enum follows a more C-inspired pattern than a Java-inspired one. This makes it possible to have “Bit Flag” enums which can use binary patterns to determine whether a particular “flag” is active in an enum value. If you had to define every possible combination of flags (i.e. MondayAndTuesday, MondayAndWednesdayAndThursday), these would be extremely tedious. So having the capacity to use undefined enum values can be really handy. It just requires a little extra work when you want a fail-fast behavior on enum types that don’t leverage these sorts of tricks.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have an enum like this public enum ConnectionState : int { Unknown =
I have a class that defines its own enum like this: public class Test
I have an enum that looks like the following: public enum EnumWeapons { Fists
I have an enum that looks like this: enum foo{ a=0, b=1, c=2, d=4
I have a with dynamic values from an Enum like: String, Int, Double, Bool,
I have an enum, that looks like this: enum Suit {Clubs, Diamonds, Hearts, Spades};
I have an enum that I'd like to display all possible values of. Is
I have enum like this [Flags] public enum Key { None = 0, A
I have enum like this: public enum ObectTypes { TypeOne, TypeTwo, TypeThree, ... TypeTwenty
If I have an enum like this public enum Hungry { Somewhat, Very, CouldEatMySocks

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.