#458 – Errors While Converting Between enum and Underlying Type

You can convert to an enum value from its underlying type by casting the underlying type (e.g. int) to the enum type.

However, when you cast a value that doesn’t have a corresponding enumerator in the type, you don’t get any sort of error.

In the example below, the Mood type has enumerators that take on the values (0,1,2,3).  But we can successfully cast a value of 4 to the Mood type.

        public enum Mood { Crabby, Happy, Petulant, Elated };

        static void Main()
        {
            int moodValue = 4;
            Mood mood;

            mood = (Mood)moodValue;
            Console.WriteLine(mood);   // 4

To detect this problem, you can check to see if the value is defined in the enumerated type using the Enum.IsDefined method.

            if (Enum.IsDefined(typeof(Mood), moodValue))
                mood = (Mood)moodValue;
            else
                Console.WriteLine("{0} is not a valid Mood value!", moodValue);

Advertisements