#982 – An Enum Type Can Store a Maximum of 32 Flags

When you store a boolean value in a bool type, each boolean value uses 1 byte, or 8 bits–the size of a bool instance.

You can be more efficient in storing boolean values by using each bit within a chunk of memory to represent a single boolean value.  You can do this quite easily by using an enum type to store a series of flags.  In the example below, a single value of type Talents can represent unique values for up to 8 different boolean values.

        [Flags]
        public enum Talents
        {
            Singing = 1,
            Dancing = 2,
            Juggling = 4,
            JokeTelling = 8,
            DoingMagic = 16,
            RollingTongue = 32,
            StiltWalking = 64,
            DoingSplits = 128
        };

You can set various bits using the bitwise OR operator.

            Talents myTalents = Talents.JokeTelling | Talents.Juggling | Talents.StiltWalking;

            // 76 = 8 + 4 + 64
            int asInt = (int)myTalents;

Note that you can store a maximum of 32 different flags in an enumerated type, because an enum type uses 4 bytes (32 bits) of storage.

Advertisements