Posted by: Cirilo Meggiolaro | 12/9/2008

Tip of the day #56 – BitArray collection

Imagine an application that manages a simple questionnaire with yes/no answers. You have many different ways to store the answers. You may use an array of Booleans, generic list of Booleans and a BitArray collection as well.

Pretty easy, straightforward and useful, the BitArray object is a collection that can store Boolean flags.

Differently from other collections, the BitArray cannot be dynamically resized and because of this behavior it does not have methods like add, remove and etc. BitArray is an indexed collection that may be used like the following code snippet:

/// Declares and instantiates a new
/// BitArray object with size equals 5.

BitArray myAnswers = new BitArray(5);

/// Add values to each item
myAnswers[0] = true;
myAnswers[1] = true;
myAnswers[2] = false;
myAnswers[3] = false;
myAnswers[4] = true;

Methods

Some methods are available for the BitArray object as described below:

  • And: The And method performs a bitwise And operation between your BitArray and a second BitArray object;

BitArray And(BitArray);

  • Or: The Or method performs a bitwise Or operation between your BitArray and a second BitArray object;

BitArray Or(BitArray);

  • Xor: The Xor method performs a bitwise exclusive Or operation between your BitArray and a second BitArray object;

BitArray Xor(BitArray);

  • Set: Defines a Boolean flag for an item in a specific index position;

Set(int, bool);

  • SetAll: Defines a Boolean flag that will be applied for all items in the collection.

SetAll(bool);

Enjoy it!


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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

Categories

%d bloggers like this: