#983 – Using a BitArray to Store a Large Collection of Boolean Values

If you need to store a set of boolean values, you can store them in array of type bool.  Each element of the array would require 8 bits, despite storing a single boolean value.

You can more efficiently store a set of boolean values in an enum type, marking the type with the Flags attribute.  This allows storing a maximum of 32 distinct boolean values.

To store a larger collection of boolean values, you can use the BitArray type.  A BitArray allows you to index into an array of boolean values, but stores the values in a more compact form than would be used by a normal array.

Below, we use an enum to index into a 50-element BitArray.

        public enum States
        {
            Alabama,
            // ...
            Wyoming
        }

            BitArray baStatesIveVisited = new BitArray(50);

            baStatesIveVisited[(int)States.Minnesota] = true;
            baStatesIveVisited[(int)States.Wisconsin] = true;
            baStatesIveVisited[(int)States.California] = true;

            States nextState = States.Alabama;
            foreach (bool b in baStatesIveVisited)
                Console.WriteLine("{0}:{1}", nextState++, b);

983-001

Advertisements