#466 – Explicitly Assigning Only Some Enumerated Values

When defining an enumerated type, you can explicitly assign values to some of the enumerators and let the compiler implicitly assign values to others.

Any enumerated values that you do not explicitly assign a value to will automatically receive a value one greater than the previous value (whether explicitly or implicitly assigned).

For the following enumerated type:

        public enum Moods
        {
            NOMOOD = 0,
            Ambivalent,
            Happy,
            Elated,
            Grouchy = 10,
            Crabby,
            Irate
        }

The Ambivalent enumerator will have a value of 1, Happy will be 2, Elated will be 3, Crabby will be 11 and Irate will be 12.

Advertisement

#465 – Dumping All Names and Values for an Enumerated Type

You can use the Enum.GetValues method to iterate through all values of an enumerated type.  You can use this method to dump out the name and value of each enumeration value in the enumerated type.

        public enum Moods
        {
            NOMOOD = 0,
            Ambivalent = 1,
            Crabby = 10,
            Grouchy = Crabby - 1,
            Happy = 42,
            SuperHappy = 2 * Happy
        }
foreach (Moods mood in Enum.GetValues(typeof(Moods)))
    Console.WriteLine("{0} - {1}", mood, (int)mood);

#464 – Getting an Enumeration’s Underlying Type at Runtime

You can use the Enum.GetUnderlyingType static method to find out what the underlying type is that is being used to store an enumerated type’s enumerated values.

        public enum Moods : byte
        {
            NOMOOD = 0,
            Ambivalent = 1,
            Crabby = 10,
            Grouchy = Crabby - 1,
            Happy = 42,
            SuperHappy = 2 * Happy
        }

        static void Main()
        {
            Type moodStorageType = Enum.GetUnderlyingType(typeof(Moods));
            var min = moodStorageType.GetField("MinValue").GetValue(null);
            var max = moodStorageType.GetField("MaxValue").GetValue(null);

            Console.WriteLine("Underlying type for Moods is: {0}", moodStorageType.FullName);
            Console.WriteLine("Values can range from {0} to {1}", min, max);
        }

#457 – Converting Between enums and their Underlying Type

When you declare an enum, by default each enumerated value is represented internally with an int.  (System.Int32 – 4 bytes).  You can convert between values of the underlying type and enum values using an explicit cast.  Because an enum is represented by an int by default, you can convert between integers and enum values.

            Mood m = (Mood)2;
            Console.WriteLine(m);   // Petulant

            m = Mood.Crabby;
            int i = (int)m;
            Console.WriteLine(i);   // 0