C# Bit Array

c# .net bitArray, examples definition, logic gates.

This is the last post of .Net collections series. You can find my last post about queues here.

Manages a compact array of bit values, which are represented as booleans, where true indicates that the bit is on (1) and false indicates the bit is off (0). Like in any other array you can access it items by index value.

BitArray implements interfaces like: ICollection, IEnumerable, ICloneable. Which I’ll cover in my next articles.

public sealed class BitArray : ICollection, IEnumerable, ICloneable


This collection can be initialized with one of six constructors. The simplest one takes an integer and initializes a new instance of the BitArray class that can hold the specified number of bit values, which are initially set to false.

BitArray array = newBitArray(16);

Now we can add items to array by selecting index or using Set() method;

        array[3] = true;     // You can set the bits with the indexer.

	array.Set(10, true); // You can set the bits with Set.


We can use count property to get number of items in array, or we can use Program class method to count all true values

CountBitArray(array); //Returns bits set to 1


Most unique function of this this class is providing methods like And(), Or(), Xor(), this allows to perform operations of logic gates.

public BitArray And(BitArray value);

For example And() method Performs the bitwise AND operation on the elements in the current BitArray against the corresponding elements in the specified BitArray.

static void Main()
     BitArray b1 = new BitArray(4);
     b1.Set(0, true);
     b1.Set(1, true);
     b1.Set(2, false);
     b1.Set(2, false);

     BitArray b2 = new BitArray(4);
     b2.Set(0, true);
     b2.Set(0, false);
     b2.Set(0, false);
     b2.Set(0, true);

     BitArray results = new BitArray(4);

    results = b1.And(b2);
     foreach(bool value in results)

This simple example returns:

  • True
  • False
  • False
  • False


BitArray is an intresting type of collection, it’s not very popular it i can be useful even if the performance isn’t the best. It allows to perform operations like crating logic gates, what can be used to create more complex things like flip-flop, and modulo counters.

This was probably the last entry about .NET collections next article will be about Unity Engine. Stay Awesome!

Author: indiedevart

Indie Games Developer

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s