Search code examples
c#booleanbitarray

Bitarray vs. bool[]


What is the advantage of using a Bitarray when you can store your bool values in a bool[]?

System.Collections.BitArray biArray = new System.Collections.BitArray(8);
biArray[4] = true;

bool[] boArray = new bool[8];
boArray[4] = true;

The bool[] seems a little more handy to me, because there exist more (extension) methods to work with a array instead of a BitArray.

I expected to find an existing question here on Stack Overflow about this, but I didn't.


Solution

  • BitArray is compact and allows you to perform bitwise operations. From the MSDN forum:

    A BitArray uses one bit for each value, while a bool[] uses one byte for each value. You can pass to the BitArray constructor either an array of bools, an array of bytes or an array of integers. You can also pass an integer value specifying the desired length and (optionally) a boolean argument that specifies if the individual bits should be set or not.