#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.

        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.


#40 – TrueString and FalseString

The System.Boolean type (bool) provides two fields that let you get string representations of the true and false values.

 string trueText = bool.TrueString;      // "True"
 string falseText = bool.FalseString;    // "False"

These fields return “True” and “False”, regardless of current regional settings or the native language of the operating system.

These values are identical to the string values returned from the System.Boolean.ToString() method, which can be called on an instance of bool.

 bool b1 = true;
 bool b2 = false;

 string true2 = b1.ToString();     // "True"
 string false2 = b2.ToString();    // "False"