Updated on

BitArray is a C# collection that stores each boolean as a single bit, so a million flags take about 125 KB where a bool[] takes about 1 MB. We create one from a size or an array, read and write bits by index, and combine whole arrays with And, Or, Xor and Not.

Single values are slower, though. Writing bits one at a time takes longer than writing to a bool[], while operations on the whole array are much faster.

To download the source code for this article, you can visit our GitHub repository.

Let’s start.

What Is a BitArray in C#?

BitArray is a class in the System.Collections namespace that manages an array of bits. Every bit is represented as a boolean value, where the value is true if the bit is on and false if the bit is off.

The bits are packed tightly. On .NET 10, a BitArray keeps them in a byte array, eight values to a byte, so a million bits need about 125 KB. A bool[] of the same length spends a full byte on each value and needs about 1 MB.

Indexes are zero-based, and the size is ours to control. We grow or shrink the array through its Length property, and reading past the end throws an ArgumentOutOfRangeException.

BitArray implements ICollection, IEnumerable and ICloneable. It isn’t generic, so a foreach loop hands us each bit as an object unless we declare the loop variable as bool, and LINQ needs a Cast<bool>() first.

The class is sealed and isn’t thread-safe.

Like ArrayList and Hashtable, it’s one of the non-generic collections in .NET, written before C# had generics.

How to Create a BitArray in C#?

BitArray class has six constructors that we can use to create a new instance.

BitArray(Int32)

With this constructor, we can initialize a new instance with a specified number of bit values:

using System.Collections;

BitArray bitArray1 = new BitArray(8);
bitArray1.Print();  // False False False False False False False False

The default value is False.

As you can see, we use the Print extension method to loop and print elements of BitArray. Extension methods go inside a static class, so we put it in one at the end of Program.cs:

public static void Print(this BitArray bitArray)
{
    foreach (bool bit in bitArray)
    {
        Console.Write(bit + " ");
    }
    Console.WriteLine();
}

BitArray(Int32, Boolean)

We use this constructor to initialize a new instance with a specified number of bit values and set these values:

BitArray bitArray2 = new BitArray(8, true);
bitArray2.Print(); // True True True True True True True True

BitArray(Byte[])

With this constructor, we can initialize a new instance that contains bit values copied from the specified array of bytes:

BitArray bitArray3 = new BitArray(new byte[1] { 2 });
bitArray3.Print(); // False True False False False False False False

One byte holds 8 bits, and the value 2 is 00000010 in binary. BitArray puts the least significant bit at index 0, so index 1 is the one that comes out True. Because Print writes the bits from index 0 upward, the output reads like the binary number written backwards.

The byte value 2 as binary 00000010, with each bit mapped to its BitArray index; index 1 is true and the printed output lists index 0 first.

BitArray index 0 is the least significant bit, so the printed order is the binary number reversed.

BitArray(Int32[])

Using this constructor, we can initialize a new instance that contains bit values copied from the specified array of 32-bit integers:

BitArray bitArray4 = new BitArray(new int[1] { 4 });
bitArray4.Print(); // False False True False False False ...

The value 4 converts to 32 bits, 00000000 00000000 00000000 00000100 in binary. Again, the lowest bit lands at index 0, so index 2 is on (True) and the other 31 bits are off (False).

BitArray(Boolean[])

If we have an array of booleans that we want to convert to a bit array, we can use this constructor:

BitArray bitArray5 = new BitArray(new bool[8]); 
bitArray5.Print(); // False False False False False False False False

Although a bool takes 8 bits (the sizeof operator returns 1 for it), every value of the boolean array maps to a single bit in BitArray.

BitArray(BitArray)

With this constructor, we can initialize a new instance that contains bit values copied from the specified BitArray:

BitArray bitArray6 = new BitArray(bitArray1);
bitArray6.Print(); // False False False False False False False False

BitArray Properties in C#

Count Property

It enables us to get the number of items in the BitArray:

BitArray bitArray = new BitArray(8);
Console.WriteLine(bitArray.Count); // 8

IsReadOnly Property

We use this property to get a value that specifies whether the BitArray is read-only:

Console.WriteLine(bitArray.IsReadOnly); // False

This property isn’t part of the ICollection interface, and it’s always false.

IsSynchronized Property

It enables us to get a value that specifies whether access to the BitArray is synchronized:

Console.WriteLine(bitArray.IsSynchronized); // False

This one is required by the ICollection interface, and it’s always false too.

Indexer

In situations where we want to get or set the value of the bit at a specific index in BitArray, we can use indexer:

bitArray[0] = true;
Console.WriteLine(bitArray[0]); // True

Length Property

With this property, we can get or set the number of items in the BitArray:

Console.WriteLine(bitArray.Length); // 8
bitArray.Length = 6;
Console.WriteLine(bitArray.Length); // 6

This property returns the same value that the Count property returns, but it can be set to a specific value. On the other hand, the Count property is read-only. If we make the array longer again, the new bits start as false.

SyncRoot Property

It enables us to get an object that can be used to synchronize access to the BitArray:

lock(bitArray.SyncRoot)
{
    foreach (var item in bitArray)
    {
        // Insert your code here.
    }
}

BitArray itself isn’t thread-safe, so when several threads share one, we lock on SyncRoot or on a lock object of our own. Our article on locking in C# covers the options.

BitArray Methods in C#

Get(Int32)

With this method, we can get the value of the bit at a specific index in the BitArray:

Console.WriteLine(bitArray.Get(0)); // Equal: Console.WriteLine(bitArray[0]);

Set(Int32, Boolean)

We use this method to set the value of the bit at a specific index in a BitArray:

bitArray.Set(0, true); // Equal: bitArray[0] = true;

SetAll(Boolean)

If we need to set all bits to the specified value, we can use this method:

bitArray.SetAll(true);
bitArray.Print(); // True True True True True True

Logical Methods

BitArray class provides us with many logical operations such as: And, Or, Xor, Not, LeftShift, and RightShift:

BitArray bitArray1 = new BitArray(new bool[] { false, false, true, true });
BitArray bitArray2 = new BitArray(new bool[] { false, true, true, false });

bitArray1.And(bitArray2).Print(); // False False True False
// bitArray1 : { False False True False }
 
bitArray1.Or(bitArray2).Print();  // False True True False
// bitArray1 : { False True True False }
bitArray1.Xor(bitArray2).Print(); // False False False False
// bitArray1 : { False False False False }
bitArray2.LeftShift(1).Print();   // False False True True
// bitArray2 : { False False True True }
bitArray2.RightShift(1).Print();  // False True True False
// bitArray2 : { False True True False }
bitArray2.Not().Print();          // True False False True

First, we use the And method to apply the And operation between two BitArray objects: bitArray1 and bitArray2. The And method returns true if both bits are true, otherwise, the result is false. So in the result, the third bit is true and the other bits are false. It also modifies bitArray1 with the result and returns it.

Secondly, we use the Or method. This method returns false if both bits are false, otherwise, the result is true, so the bitArray1 become False True True False.

Next, we apply the Xor method that returns false if both bits are the same, otherwise, the result is true. As we can see bitArray1 becomes False False False False.

Then, we use the LeftShift method on bitArray2 object. As the name suggests, this method shifts the bits to the left and the empty places become false.

Finally, we use the RightShift method on bitArray2 object. This method shifts the bits to the right, and also the empty places become false.

After the shifts, the Not method flips every bit in bitArray2, so False True True False becomes True False False True.

The shift names can look backwards in this output. LeftShift moves every bit to a higher index, so in our printed line the bits seem to move right. The name follows the binary number, where index 0 is the rightmost digit, while Print writes index 0 first. Both shift methods arrived in .NET Core 2.0, so code that still targets .NET Framework doesn’t have them.

And, Or and Xor also expect two arrays of the same length. If the lengths differ, they throw an ArgumentException.

HasAllSet() and HasAnySet()

Since .NET 8, we can check the whole array in one call:

BitArray flags = new BitArray(4);
Console.WriteLine(flags.HasAnySet()); // False

flags[2] = true;
Console.WriteLine(flags.HasAnySet()); // True
Console.WriteLine(flags.HasAllSet()); // False

HasAnySet returns true if at least one bit is on, and HasAllSet returns true only if every bit is on. An empty BitArray counts as all set, because none of its bits is off.

CopyTo(Array, Int32)

To turn bits back into numbers, we copy them into a byte[], an int[] or a bool[]:

BitArray bits = new BitArray(8);
bits[1] = true;
bits[3] = true;

byte[] bytes = new byte[1];
bits.CopyTo(bytes, 0);

Console.WriteLine(bytes[0]); // 10

Index 1 is worth 2 and index 3 is worth 8, so the byte holds 10. The bit order matches the constructors, which makes CopyTo the reverse of new BitArray(byte[]).

The same method answers a question BitArray has no method for on .NET 10: how many bits are on? We copy the bits into an int[] and count each element with BitOperations.PopCount(), which needs using System.Numerics; at the top of the file. The helper goes in the same static class as Print:

public static int CountSetBits(BitArray bits)
{
    int[] words = new int[(bits.Length + 31) / 32];
    bits.CopyTo(words, 0);

    int count = 0;
    foreach (int word in words)
    {
        count += BitOperations.PopCount((uint)word);
    }

    return count;
}

For new BitArray(new byte[] { 2, 255 }), this returns 9: one bit from the 2 and eight from the 255. The upcoming .NET 11 adds a PopCount() method to BitArray itself, so on that version the helper becomes a single call.

Should We Use BitArray or bool[] in C#?

It depends on what we do with the bits.

On memory, BitArray wins for large arrays. It stores one bit per value, while a bool[] spends a whole byte on each one, so the bool[] needs eight times more memory. At 100 million values, that’s about 12.5 MB against 100 MB.

Single values go to bool[]. Setting values one by one in a loop was two to four times slower on a BitArray in our run, because every write has to find the right byte, mask the right bit inside it and update a version counter.

Whole-array operations swing back to BitArray. And, Or, Xor and Not work on many bits per instruction and use SIMD where the CPU supports it, so combining two arrays of a million values took a few microseconds instead of about a millisecond for a bool[] loop.

So we pick bool[] for small arrays we read and write all the time, and BitArray for large sets of flags or whole-set logic.

Let’s check both sides with the BenchmarkDotNet library. The first benchmark sets every value one at a time:

[MemoryDiagnoser(false)]
public class BitArrayBenchmark
{
    [Params(1000, 1000_000, 100_000_000)]
    public int Size { get; set; }

    [Benchmark]
    public void BitArray()
    {
        BitArray bitArray = new BitArray(Size);
        for (int i = 0; i < bitArray.Length; i++)
        {
            bitArray[i] = true;
        }
    }

    [Benchmark]
    public void BoolArray()
    {
        bool[] boolArray = new bool[Size];
        for (int i = 0; i < boolArray.Length; i++)
        {
            boolArray[i] = true;
        }
    }
}

The benchmark class goes in its own console project. We add the BenchmarkDotNet package to it, start the class file with using BenchmarkDotNet.Attributes; and using System.Collections;, and call BenchmarkRunner.Run<BitArrayBenchmark>(); from its Program.cs, after using BenchmarkDotNet.Running;. After running the benchmark in Release mode we can inspect the results:

| Method    | Size      | Mean             | Error         | StdDev        | Allocated   |
|---------- |---------- |-----------------:|--------------:|--------------:|------------:|
| BitArray  | 1000      |       1,067.8 ns |       7.37 ns |       6.54 ns |       152 B |
| BoolArray | 1000      |         311.0 ns |       6.13 ns |       5.74 ns |      1024 B |
| BitArray  | 1000000   |   1,098,766.2 ns |   6,136.22 ns |   5,739.82 ns |    125036 B |
| BoolArray | 1000000   |     532,272.1 ns |   7,875.40 ns |   7,366.65 ns |   1000108 B |
| BitArray  | 100000000 | 107,784,045.0 ns | 261,925.36 ns | 444,769.18 ns |  12500128 B |
| BoolArray | 100000000 |  30,840,462.7 ns | 201,688.22 ns | 188,659.29 ns | 100000180 B |

We notice that BitArray is memory efficient over bool[], because in BitArray, we need 1 bit to store a value, but in the bool[] we need 8 bits. This means that bool[] needs x8 more memory than BitArray. 

On the other hand, bool[] is faster here. That’s because of how BitArray stores its values. On .NET 10, they’re packed into a byte array (earlier versions used an array of 32-bit integers), so every write has to find the right byte, mask the right bit and update a version counter. Writing one bool to an array takes less work than that.

The picture changes when we work on whole arrays. The second benchmark combines two arrays with a logical AND, once with the And method and once with a loop over bool[]. It goes in the same file, and Program.cs gets a second call, BenchmarkRunner.Run<BitArrayAndBenchmark>();:

[MemoryDiagnoser(false)]
public class BitArrayAndBenchmark
{
    private BitArray _bitsLeft = null!;
    private BitArray _bitsRight = null!;
    private bool[] _boolsLeft = null!;
    private bool[] _boolsRight = null!;

    [Params(1000, 1000_000, 100_000_000)]
    public int Size { get; set; }

    [GlobalSetup]
    public void Setup()
    {
        _bitsLeft = new BitArray(Size, true);
        _bitsRight = new BitArray(Size, true);
        _boolsLeft = new bool[Size];
        _boolsRight = new bool[Size];
        Array.Fill(_boolsLeft, true);
        Array.Fill(_boolsRight, true);
    }

    [Benchmark]
    public void BitArrayAnd()
    {
        _bitsLeft.And(_bitsRight);
    }

    [Benchmark]
    public void BoolArrayAnd()
    {
        for (int i = 0; i < _boolsLeft.Length; i++)
        {
            _boolsLeft[i] &= _boolsRight[i];
        }
    }
}
| Method       | Size      | Mean              | Error           | StdDev          | Allocated |
|------------- |---------- |------------------:|----------------:|----------------:|----------:|
| BitArrayAnd  | 1000      |          8.192 ns |       0.0631 ns |       0.0560 ns |         - |
| BoolArrayAnd | 1000      |        881.839 ns |       1.4919 ns |       1.2458 ns |         - |
| BitArrayAnd  | 1000000   |      2,631.536 ns |      52.3545 ns |      73.3937 ns |         - |
| BoolArrayAnd | 1000000   |    888,442.062 ns |  12,504.5342 ns |  11,084.9439 ns |         - |
| BitArrayAnd  | 100000000 |  1,127,710.877 ns |   8,982.1587 ns |   7,500.5093 ns |         - |
| BoolArrayAnd | 100000000 | 88,333,889.286 ns | 269,455.8011 ns | 238,865.5493 ns |         - |

This time BitArray is far ahead at every size. And works on whole bytes and vectors at once, while the bool[] loop touches one value per iteration. If our code mostly combines, inverts or tests whole sets of flags, BitArray is the faster choice as well as the smaller one.

For a fixed set of up to 32 flags, there’s a lighter option. BitVector32 in System.Collections.Specialized is a struct that holds exactly 32 bits, and a [Flags] enum does a similar job with named values. Microsoft’s BitArray documentation draws the line: “if the number of required bit flags is unknown, is variable, or is greater than 32, use BitArray instead.”

BitArraybool[]
Memory per value1 bit1 byte (8 bits)
Setting values one by oneSlower (byte lookup, bit mask)Faster
Combining whole arraysAnd, Or, Xor, Not built in, vectorizedA loop we write ourselves
Other bulk methodsSetAll, LeftShift, RightShift, HasAllSet, HasAnySetArray.Fill, Array.Exists
Generic and LINQ-readyNo, needs Cast<bool>()Yes
Changing the sizeSet LengthArray.Resize creates a new array
Pick it forLarge sets of flags, whole-set logic, tight memorySmall arrays read and written all the time

Therefore, the decision on which one to use really depends on what we need.

Conclusion

We’ve learned about the BitArray class in C#: its constructors, properties and methods, the order it keeps its bits in, and how it compares with bool[].

For small arrays we touch one value at a time, bool[] is still the faster choice. For large sets of flags and whole-array logic, BitArray takes an eighth of the memory and runs the bulk operations far faster.

Tested with .NET 10.0.10, BenchmarkDotNet 0.15.8 and xUnit 2.9.3.