#191 – Changing the Underlying Type of an enum

When you declare an enum, by default each enumerated value is represented internally with an int.  (System.Int32 – 4 bytes).  But you can use any of the following types: byte, sbyte, short, ushort, uint, long, or ulong.

        public enum Mood { Crabby, Happy, Petulant, Elated };   // type is int

        public enum MoodByte : byte { Crabby, Happy, Petulant, Elated };

        static void Main()
        {
            // 4 bytes
            Console.WriteLine("Each element is {0} bytes", sizeof(Mood));

            // 1 byte
            Console.WriteLine("Each element is {0} bytes", sizeof(MoodByte));
        }
Advertisement