System.Collections.BitArray Class

Assembly: Mscorlib.dll
Namespace: System.Collections
Summary
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).
C# Syntax:
[Serializable]
public sealed class BitArray : ICollection, IEnumerable, ICloneable
Thread Safety
Public static (non-instance) members of this type are safe for multithreaded operations. Instance members are not guaranteed to be thread-safe.

This implementation does not provide a synchronized (thread-safe) wrapper for a BitArray.

Enumerating through a collection is intrinsically not a thread-safe procedure. Even when a collection is synchronized, other threads could still modify the collection, which causes the enumerator to throw an exception. To guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads.

Remarks
The size of a BitArray is controlled by the client; indexing past the end of the BitArray throws an ArgumentException.

Indexes in this collection are zero-based.

Example
The following example shows how to create and initialize a BitArray and how to print out its values.
 using System;
 using System.Collections;
 public class SamplesBitArray  {
 
    public static void Main()  {
 
       // Creates and initializes several BitArrays.
       BitArray myBA1 = new BitArray( 5 );
 
       BitArray myBA2 = new BitArray( 5, false );
 
       byte[] myBytes = new byte[5] { 1, 2, 3, 4, 5 };
       BitArray myBA3 = new BitArray( myBytes );
 
       bool[] myBools = new bool[5] { true, false, true, true, false };
       BitArray myBA4 = new BitArray( myBools );
 
       int[]  myInts  = new int[5] { 6, 7, 8, 9, 10 };
       BitArray myBA5 = new BitArray( myInts );
 
       // Displays the properties and values of the BitArrays.
       Console.WriteLine( "myBA1" );
       Console.WriteLine( "\tCount:    {0}", myBA1.Count );
       Console.WriteLine( "\tLength:   {0}", myBA1.Length );
       Console.WriteLine( "\tValues:" );
       PrintValues( myBA1, 8 );
 
       Console.WriteLine( "myBA2" );
       Console.WriteLine( "\tCount:    {0}", myBA2.Count );
       Console.WriteLine( "\tLength:   {0}", myBA2.Length );
       Console.WriteLine( "\tValues:" );
       PrintValues( myBA2, 8 );
 
       Console.WriteLine( "myBA3" );
       Console.WriteLine( "\tCount:    {0}", myBA3.Count );
       Console.WriteLine( "\tLength:   {0}", myBA3.Length );
       Console.WriteLine( "\tValues:" );
       PrintValues( myBA3, 8 );
 
       Console.WriteLine( "myBA4" );
       Console.WriteLine( "\tCount:    {0}", myBA4.Count );
       Console.WriteLine( "\tLength:   {0}", myBA4.Length );
       Console.WriteLine( "\tValues:" );
       PrintValues( myBA4, 8 );
 
       Console.WriteLine( "myBA5" );
       Console.WriteLine( "\tCount:    {0}", myBA5.Count );
       Console.WriteLine( "\tLength:   {0}", myBA5.Length );
       Console.WriteLine( "\tValues:" );
       PrintValues( myBA5, 8 );
    }
 
 
    public static void PrintValues( IEnumerable myList, int myWidth )  {
       System.Collections.IEnumerator myEnumerator = myList.GetEnumerator();
       int i = myWidth;
       while ( myEnumerator.MoveNext() )  {
          if ( i <= 0 )  {
             i = myWidth;
             Console.WriteLine();
          }
          i--;
          Console.Write( "\t{0}", myEnumerator.Current );
       }
       Console.WriteLine();
    }
 }
 /* 
 This code produces the following output.
 
 myBA1
     Count:    5
     Length:   5
     Values:
     False    False    False    False    False
 myBA2
     Count:    5
     Length:   5
     Values:
     False    False    False    False    False
 myBA3
     Count:    40
     Length:   40
     Values:
     True    False    False    False    False    False    False    False
     False    True    False    False    False    False    False    False
     True    True    False    False    False    False    False    False
     False    False    True    False    False    False    False    False
     True    False    True    False    False    False    False    False
 myBA4
     Count:    5
     Length:   5
     Values:
     True    False    True    True    False
 myBA5
     Count:    160
     Length:   160
     Values:
     False    True    True    False    False    False    False    False
     False    False    False    False    False    False    False    False
     False    False    False    False    False    False    False    False
     False    False    False    False    False    False    False    False
     True    True    True    False    False    False    False    False
     False    False    False    False    False    False    False    False
     False    False    False    False    False    False    False    False
     False    False    False    False    False    False    False    False
     False    False    False    True    False    False    False    False
     False    False    False    False    False    False    False    False
     False    False    False    False    False    False    False    False
     False    False    False    False    False    False    False    False
     True    False    False    True    False    False    False    False
     False    False    False    False    False    False    False    False
     False    False    False    False    False    False    False    False
     False    False    False    False    False    False    False    False
     False    True    False    True    False    False    False    False
     False    False    False    False    False    False    False    False
     False    False    False    False    False    False    False    False
     False    False    False    False    False    False    False    False
 */ 

    
See also:
System.Collections Namespace

System.Collections.BitArray Member List:

Public Constructors
ctor #1 Overloaded:
.ctor(BitArray bits)

Initializes a new instance of the BitArray class that contains bit values copied from the specified BitArray.
ctor #2 Overloaded:
.ctor(bool[] values)

Initializes a new instance of the BitArray class that contains bit values copied from the specified array of Booleans.
ctor #3 Overloaded:
.ctor(byte[] bytes)

Initializes a new instance of the BitArray class that contains bit values copied from the specified array of bytes.
ctor #4 Overloaded:
.ctor(int length)

Initializes a new instance of the BitArray class that can hold the specified number of bit values, which are initially set to false.
ctor #5 Overloaded:
.ctor(int[] values)

Initializes a new instance of the BitArray class that contains bit values copied from the specified array of 32-bit integers.
ctor #6 Overloaded:
.ctor(int length, bool defaultValue)

Initializes a new instance of the BitArray class that can hold the specified number of bit values, which are initially set to the specified value.
Public Properties
Count Read-only

Gets the number of elements contained in the BitArray.
IsReadOnly Read-only

Gets a value indicating whether the BitArray is read-only.
IsSynchronized Read-only

Gets a value indicating whether access to the BitArray is synchronized (thread-safe).
Item Read-write

Gets or sets the value of the bit at a specific position in the BitArray.
Length Read-write

Gets or sets the number of elements in the BitArray.
SyncRoot Read-only

Gets an object that can be used to synchronize access to the BitArray.
Public Methods
And Performs the bitwise AND operation on the elements in the current BitArray against the corresponding elements in the specified BitArray.
Clone Creates a shallow copy of the BitArray.
CopyTo Copies the entire BitArray to a compatible one-dimensional Array, starting at the specified index of the target array.
Equals
(inherited from System.Object)
See base class member description: System.Object.Equals

Derived from System.Object, the primary base class for all objects.
Get Gets the value of the bit at a specific position in the BitArray.
GetEnumerator Returns an enumerator that can iterate through the BitArray.
GetHashCode
(inherited from System.Object)
See base class member description: System.Object.GetHashCode

Derived from System.Object, the primary base class for all objects.
GetType
(inherited from System.Object)
See base class member description: System.Object.GetType

Derived from System.Object, the primary base class for all objects.
Not Inverts all the bit values in the current BitArray, so that elements set to true are changed to false, and elements set to false are changed to true.
Or Performs the bitwise OR operation on the elements in the current BitArray against the corresponding elements in the specified BitArray.
Set Sets the bit at a specific position in the BitArray to the specified value.
SetAll Sets all bits in the BitArray to the specified value.
ToString
(inherited from System.Object)
See base class member description: System.Object.ToString

Derived from System.Object, the primary base class for all objects.
Xor Performs the bitwise eXclusive OR operation on the elements in the current BitArray against the corresponding elements in the specified BitArray.
Protected Methods
Finalize
(inherited from System.Object)
See base class member description: System.Object.Finalize

Derived from System.Object, the primary base class for all objects.
MemberwiseClone
(inherited from System.Object)
See base class member description: System.Object.MemberwiseClone

Derived from System.Object, the primary base class for all objects.

Hierarchy:


System.Collections.BitArray Member Details

Overloaded ctor #1
Summary
Initializes a new instance of the BitArray class that contains bit values copied from the specified BitArray.
C# Syntax:
public BitArray(BitArray(
   BitArray bits
);
Parameters:

bits

The BitArray to copy.

Exceptions
Exception Type Condition
ArgumentNullException bits is null.

Return to top


Overloaded ctor #2
Summary
Initializes a new instance of the BitArray class that contains bit values copied from the specified array of Booleans.
C# Syntax:
public BitArray(
   bool[] values
);
Parameters:

values

An array of Booleans to copy.

Exceptions
Exception Type Condition
ArgumentNullException values is null.

Return to top


Overloaded ctor #3
Summary
Initializes a new instance of the BitArray class that contains bit values copied from the specified array of bytes.
C# Syntax:
public BitArray(
   byte[] bytes
);
Parameters:

bytes

An array of bytes containing the values to copy, where each byte represents eight consecutive bits.

Exceptions
Exception Type Condition
ArgumentNullException bytes is null.
Remarks
The first byte in the array represents bits 0 through 7, the second byte represents bits 8 through 15, and so on. The Least Significant Bit of each byte represents the lowest index value: " bytes [0] & 1" represents bit 0, " bytes [0] & 2" represents bit 1, " bytes [0] & 4" represents bit 2, and so on.

Return to top


Overloaded ctor #4
Summary
Initializes a new instance of the BitArray class that can hold the specified number of bit values, which are initially set to false.
C# Syntax:
public BitArray(
   int length
);
Parameters:

length

The number of bit values in the new BitArray.

Exceptions
Exception Type Condition
ArgumentOutOfRangeException length is less than zero.

Return to top


Overloaded ctor #5
Summary
Initializes a new instance of the BitArray class that contains bit values copied from the specified array of 32-bit integers.
C# Syntax:
public BitArray(
   int[] values
);
Parameters:

values

An array of integers containing the values to copy, where each integer represents 32 consecutive bits.

Exceptions
Exception Type Condition
ArgumentNullException values is null.
Remarks
The number in the first values array element represents bits 0 through 31, the second number in the array represents bits 32 through 63, and so on. The Least Significant Bit of each integer represents the lowest index value: " values [0] & 1" represents bit 0, " values [0] & 2" represents bit 1, " values [0] & 4" represents bit 2, and so on.

Return to top


Overloaded ctor #6
Summary
Initializes a new instance of the BitArray class that can hold the specified number of bit values, which are initially set to the specified value.
C# Syntax:
public BitArray(
   int length,
   bool defaultValue
);
Parameters:

length

The number of bit values in the new BitArray.

defaultValue

The Boolean value to assign to each bit.

Exceptions
Exception Type Condition
ArgumentOutOfRangeException length is less than zero.

Return to top


Property: Count (read-only)
Summary
Gets the number of elements contained in the BitArray.
C# Syntax:
public int Count {get;}
Implements:
ICollection.Count
Remarks
BitArray.Length and BitArray.Count return the same value. BitArray.Length can be set to a specific value, but BitArray.Count is read-only.

Return to top


Property: IsReadOnly (read-only)
Summary
Gets a value indicating whether the BitArray is read-only.
C# Syntax:
public bool IsReadOnly {get;}
Remarks
BitArray implements the BitArray.IsReadOnly property because it is required by the IList interface.

A collection that is read-only does not allow the addition, removal, or modification of elements after the collection is created.

Return to top


Property: IsSynchronized (read-only)
Summary
Gets a value indicating whether access to the BitArray is synchronized (thread-safe).
C# Syntax:
public bool IsSynchronized {get;}
Implements:
ICollection.IsSynchronized
Remarks
BitArray implements the BitArray.IsSynchronized property because it is required by the ICollection interface.

Enumerating through a collection is intrinsically not a thread-safe procedure. Even when a collection is synchronized, other threads could still modify the collection, which causes the enumerator to throw an exception. To guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads.

The following code example shows how to lock the collection using the BitArray.SyncRoot during the entire enumeration:

              BitArray myCollection = new BitArray();
               lock( myCollection.SyncRoot ) {
               foreach ( Object item in myCollection ) {
               // Insert your code here.
               }
              }
            
See also:
BitArray.SyncRoot

Return to top


Property: Item (read-write)
Summary
Gets or sets the value of the bit at a specific position in the BitArray.
C# Syntax:
public bool this[int index] {get; set;}
Parameters:

index

The zero-based index of the value to get or set.

Exceptions
Exception Type Condition
ArgumentOutOfRangeException index is less than zero.

-or-

index is equal to or greater than BitArray.Count.

Remarks
This property provides the ability to access a specific element in the collection by using the following syntax: myCollection[index] .
See also:
BitArray.Count

Return to top


Property: Length (read-write)
Summary
Gets or sets the number of elements in the BitArray.
C# Syntax:
public int Length {get; set;}
Exceptions
Exception Type Condition
ArgumentOutOfRangeException The property is set to a value that is less than zero.
Remarks
BitArray.Length and BitArray.Count return the same value. BitArray.Length can be set to a specific value, but BitArray.Count is read-only.

If BitArray.Length is set to a value that is less than BitArray.Count, the BitArray is truncated and the elements after the index value -1 are deleted.

If BitArray.Length is set to a value that is greater than BitArray.Count, the new elements are set to false.

Return to top


Property: SyncRoot (read-only)
Summary
Gets an object that can be used to synchronize access to the BitArray.
C# Syntax:
public object SyncRoot {get;}
Implements:
ICollection.SyncRoot
Remarks
Derived classes can provide their own synchronized version of the BitArray using the BitArray.SyncRoot property. The synchronizing code must perform operations on the BitArray.SyncRoot of the BitArray, not directly on the BitArray. This ensures proper operation of collections that are derived from other objects. Specifically, it maintains proper synchronization with other threads that might be simultaneously modifying the BitArray object.

Enumerating through a collection is intrinsically not a thread-safe procedure. Even when a collection is synchronized, other threads could still modify the collection, which causes the enumerator to throw an exception. To guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads.

The following code example shows how to lock the collection using the BitArray.SyncRoot during the entire enumeration:

              BitArray myCollection = new BitArray();
               lock( myCollection.SyncRoot ) {
               foreach ( Object item in myCollection ) {
               // Insert your code here.
               }
              }
            
See also:
BitArray.IsSynchronized

Return to top


Method: And(
   BitArray value
)
Summary
Performs the bitwise AND operation on the elements in the current BitArray against the corresponding elements in the specified BitArray.
C# Syntax:
public BitArray And(
   BitArray value
);
Parameters:

value

The BitArray with which to perform the bitwise AND operation.

Return Value:
A BitArray containing the result of the bitwise AND operation on the elements in the current BitArray against the corresponding elements in the specified BitArray.
Exceptions
Exception Type Condition
ArgumentNullException value is null.
ArgumentException value and the current BitArray do not have the same number of elements.
Remarks
The bitwise AND operation returns true if both operands are true, and returns false if one or both operands are false.
Example
The following example shows how to apply AND to two BitArray instances.
 using System;
 using System.Collections;
 public class SamplesBitArray  {
 
    public static void Main()  {
 
       // Creates and initializes two BitArrays of the same size.
       BitArray myBA1 = new BitArray( 4 );
       BitArray myBA2 = new BitArray( 4 );
       myBA1[0] = myBA1[1] = false;
       myBA1[2] = myBA1[3] = true;
       myBA2[0] = myBA2[2] = false;
       myBA2[1] = myBA2[3] = true;
 
       // Performs a bitwise AND operation between BitArray instances of the same size.
       Console.WriteLine( "Initial values" );
       Console.Write( "myBA1:" );
       PrintValues( myBA1, 8 );
       Console.Write( "myBA2:" );
       PrintValues( myBA2, 8 );
       Console.WriteLine();
 
       Console.WriteLine( "Result" );
       Console.Write( "AND:" );
       PrintValues( myBA1.And( myBA2 ), 8 );
       Console.WriteLine();
 
       Console.WriteLine( "After AND" );
       Console.Write( "myBA1:" );
       PrintValues( myBA1, 8 );
       Console.Write( "myBA2:" );
       PrintValues( myBA2, 8 );
       Console.WriteLine();
 
       // Performing AND between BitArray instances of different sizes returns an exception.
       try  {
          BitArray myBA3 = new BitArray( 8 );
          myBA3[0] = myBA3[1] = myBA3[2] = myBA3[3] = false;
          myBA3[4] = myBA3[5] = myBA3[6] = myBA3[7] = true;
          myBA1.And( myBA3 );
       } catch ( Exception myException )  {
          Console.WriteLine("Exception: " + myException.ToString());
       }
    }
 
 
    public static void PrintValues( IEnumerable myList, int myWidth )  {
       System.Collections.IEnumerator myEnumerator = myList.GetEnumerator();
       int i = myWidth;
       while ( myEnumerator.MoveNext() )  {
          if ( i <= 0 )  {
             i = myWidth;
             Console.WriteLine();
          }
          i--;
          Console.Write( "\t{0}", myEnumerator.Current );
       }
       Console.WriteLine();
    }
 }
 /* 
 This code produces the following output.
 
 Initial values
 myBA1:    False    False    True    True
 myBA2:    False    True    False    True
 
 Result
 AND:    False    False    False    True
 
 After AND
 myBA1:    False    False    False    True
 myBA2:    False    True    False    True
 
 Exception: System.ArgumentException: Array lengths must be the same.
    at System.Collections.BitArray.And(BitArray value) in <UnknownName>:line 0
    at SamplesBitArray.Main()
 */ 

    

Return to top


Method: Clone()
Summary
Creates a shallow copy of the BitArray.
C# Syntax:
public object Clone();
Return Value:
A shallow copy of the BitArray.
Implements:
ICloneable.Clone
Remarks
A shallow copy of a collection copies only the elements of the collection, whether they are reference types or value types, but it does not copy the objects that the references refer to. The references in the new collection point to the same objects that the references in the original collection point to.

In contrast, a deep copy of a collection copies the elements and everything directly or indirectly referenced by the elements.

Return to top


Method: CopyTo(
   Array array,
   int index
)
Summary
Copies the entire BitArray to a compatible one-dimensional Array, starting at the specified index of the target array.
C# Syntax:
public void CopyTo(
   Array array,
   int index
);
Parameters:

array

The one-dimensional Array that is the destination of the elements copied from BitArray. The Array must have zero-based indexing.

index

The zero-based index in array at which copying begins.

Exceptions
Exception Type Condition
ArgumentNullException array is null.
ArgumentOutOfRangeException index is less than zero.
ArgumentException array is multidimensional.

-or-

index is equal to or greater than the length of array.

-or-

The number of elements in the source BitArray is greater than the available space from index to the end of the destination array.

InvalidCastException The type of the source BitArray cannot be cast automatically to the type of the destination array.
Implements:
ICollection.CopyTo
Remarks
The specified array must be of a compatible type. Only bool, int and byte types of arrays are supported.

This method uses Array.Copy to copy the elements.

Example
The following example shows how to copy a BitArray into a one-dimensional Array.
 using System;
 using System.Collections;
 public class SamplesBitArray  {
 
    public static void Main()  {
 
       // Creates and initializes the source BitArray.
       BitArray myBA = new BitArray( 4 );
       myBA[0] = myBA[1] = myBA[2] = myBA[3] = true;
 
       // Creates and initializes the one-dimensional target Array of type Boolean.
       Array myBoolArray = Array.CreateInstance( typeof(bool), 8 );
       myBoolArray.SetValue( false, 0 );
       myBoolArray.SetValue( false, 1 );
 
       // Displays the values of the target Array.
       Console.WriteLine( "The target Boolean Array contains the following (before and after copying):" );
       PrintValues( myBoolArray, '\t' );
 
       // Copies the entire source BitArray to the target BitArray, starting at index 3.
       myBA.CopyTo( myBoolArray, 3 );
 
       // Displays the values of the target Array.
       PrintValues( myBoolArray, '\t' );
 
       // Creates and initializes the one-dimensional target Array of type integer.
       Array myIntArray = Array.CreateInstance( typeof(int), 8 );
       myIntArray.SetValue( 42, 0 );
       myIntArray.SetValue( 43, 1 );
 
       // Displays the values of the target Array.
       Console.WriteLine( "The target Boolean Array contains the following (before and after copying):" );
       PrintValues( myIntArray, '\t' );
 
       // Copies the entire source BitArray to the target BitArray, starting at index 3.
       myBA.CopyTo( myIntArray, 3 );
 
       // Displays the values of the target Array.
       PrintValues( myIntArray, '\t' );
 
       // Creates and initializes the one-dimensional target Array of type integer.
       Array myByteArray = Array.CreateInstance( typeof(byte), 8 );
       myByteArray.SetValue( (byte) 10, 0 );
       myByteArray.SetValue( (byte) 11, 1 );
 
       // Displays the values of the target Array.
       Console.WriteLine( "The target Boolean Array contains the following (before and after copying):" );
       PrintValues( myByteArray, '\t' );
 
       // Copies the entire source BitArray to the target BitArray, starting at index 3.
       myBA.CopyTo( myByteArray, 3 );
 
       // Displays the values of the target Array.
       PrintValues( myByteArray, '\t' );
 
       // Returns an exception if the array is not of type Boolean, integer or byte.
       try  {
          Array myStringArray=Array.CreateInstance( typeof(String), 8 );
          myStringArray.SetValue( "Hello", 0 );
          myStringArray.SetValue( "World", 1 );
          myBA.CopyTo( myStringArray, 3 );
       } catch ( Exception myException )  {
          Console.WriteLine("Exception: " + myException.ToString());
       }
    }
 
 
    public static void PrintValues( Array myArr, char mySeparator )  {
       System.Collections.IEnumerator myEnumerator = myArr.GetEnumerator();
       int i = 0;
       int cols = myArr.GetLength( myArr.Rank - 1 );
       while ( myEnumerator.MoveNext() )  {
          if ( i < cols )  {
             i++;
          } else  {
             Console.WriteLine();
             i = 1;
          }
          Console.Write( "{0}{1}", mySeparator, myEnumerator.Current );
       }
       Console.WriteLine();
    }
 }
 /* 
 This code produces the following output.
 
 The target Boolean Array contains the following (before and after copying):
     False    False    False    False    False    False    False    False
     False    False    False    True    True    True    True    False
 The target Boolean Array contains the following (before and after copying):
     42    43    0    0    0    0    0    0
     42    43    0    15    0    0    0    0
 The target Boolean Array contains the following (before and after copying):
     10    11    0    0    0    0    0    0
     10    11    0    15    0    0    0    0
 Exception: System.ArgumentException: Only supported copyto on bit arrays are bool[], int[] and byte[].
    at System.Collections.BitArray.CopyTo(Array array, Int32 index) in <UnknownName>:line 0
    at SamplesBitArray.Main()
 */

    
See also:
Array

Return to top


Method: Equals(
   object obj
)
Inherited
See base class member description: System.Object.Equals
C# Syntax:
public virtual bool Equals(
   object obj
);

For more information on members inherited from System.Object click on the link above.

Return to top


Method: Finalize()
Inherited
See base class member description: System.Object.Finalize
C# Syntax:
~BitArray();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: Get(
   int index
)
Summary
Gets the value of the bit at a specific position in the BitArray.
C# Syntax:
public bool Get(
   int index
);
Parameters:

index

The zero-based index of the value to get.

Return Value:
The value of the bit at position index.
Exceptions
Exception Type Condition
ArgumentOutOfRangeException index is less than zero.

-or-

index is greater than or equal to the number of elements in the BitArray.

Example
The following example shows how to set and get specific elements in a BitArray.
 using System;
 using System.Collections;
 public class SamplesBitArray  {
 
    public static void Main()  {
 
       // Creates and initializes a BitArray.
       BitArray myBA = new BitArray( 5 );
 
       // Displays the properties and values of the BitArray.
       Console.WriteLine( "myBA values:" );
       PrintIndexAndValues( myBA );
 
       // Sets all the elements to true.
       myBA.SetAll( true );
 
       // Displays the properties and values of the BitArray.
       Console.WriteLine( "After setting all elements to true," );
       PrintIndexAndValues( myBA );
 
       // Sets the last index to false.
       myBA.Set( myBA.Count - 1, false );
 
       // Displays the properties and values of the BitArray.
       Console.WriteLine( "After setting the last element to false," );
       PrintIndexAndValues( myBA );
 
       // Gets the value of the last two elements.
       Console.WriteLine( "The last two elements are: " );
       Console.WriteLine( "\tat index {0} : {1}", myBA.Count - 2, myBA.Get( myBA.Count - 2 ) );
       Console.WriteLine( "\tat index {0} : {1}", myBA.Count - 1, myBA.Get( myBA.Count - 1 ) );
    }
 
 
    public static void PrintIndexAndValues( IEnumerable myList )  {
       int i = 0;
       System.Collections.IEnumerator myEnumerator = myList.GetEnumerator();
       while ( myEnumerator.MoveNext() )
          Console.WriteLine( "\t[{0}]:\t{1}", i++, myEnumerator.Current );
       Console.WriteLine();
    }
 }
 /* 
 This code produces the following output.
 
 myBA values:
     [0]:    False
     [1]:    False
     [2]:    False
     [3]:    False
     [4]:    False
 
 After setting all elements to true,
     [0]:    True
     [1]:    True
     [2]:    True
     [3]:    True
     [4]:    True
 
 After setting the last element to false,
     [0]:    True
     [1]:    True
     [2]:    True
     [3]:    True
     [4]:    False
 
 The last two elements are: 
     at index 3 : True
     at index 4 : False
 */ 

    

Return to top


Method: GetEnumerator()
Summary
Returns an enumerator that can iterate through the BitArray.
C# Syntax:
public IEnumerator GetEnumerator();
Return Value:
An IEnumerator for the entire BitArray.
Implements:
IEnumerable.GetEnumerator
Remarks
Enumerators only allow reading the data in the collection. Enumerators cannot be used to modify the underlying collection.

Initially, the enumerator is positioned before the first element in the collection. IEnumerator.Reset also brings the enumerator back to this position. At this position, calling IEnumerator.Current throws an exception. Therefore, you must call IEnumerator.MoveNext to advance the enumerator to the first element of the collection before reading the value of IEnumerator.Current.

IEnumerator.Current returns the same object until either IEnumerator.MoveNext or IEnumerator.Reset is called. IEnumerator.MoveNext sets IEnumerator.Current to the next element.

After the end of the collection is passed, the enumerator is positioned after the last element in the collection, and calling IEnumerator.MoveNext returns false. If the last call to IEnumerator.MoveNext returned false, calling IEnumerator.Current throws an exception. To set IEnumerator.Current to the first element of the collection again, you can call IEnumerator.Reset followed by IEnumerator.MoveNext.

An enumerator remains valid as long as the collection remains unchanged. If changes are made to the collection, such as adding, modifying or deleting elements, the enumerator is irrecoverably invalidated and the next call to IEnumerator.MoveNext or IEnumerator.Reset throws an InvalidOperationException. If the collection is modified between IEnumerator.MoveNext and IEnumerator.Current, IEnumerator.Current will return the element that it is set to, even if the enumerator is already invalidated.

The enumerator does not have exclusive access to the collection; therefore, enumerating through a collection is intrinsically not a thread-safe procedure. Even when a collection is synchronized, other threads could still modify the collection, which causes the enumerator to throw an exception. To guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads.

See also:
IEnumerator

Return to top


Method: GetHashCode()
Inherited
See base class member description: System.Object.GetHashCode
C# Syntax:
public virtual int GetHashCode();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: GetType()
Inherited
See base class member description: System.Object.GetType
C# Syntax:
public Type GetType();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: MemberwiseClone()
Inherited
See base class member description: System.Object.MemberwiseClone
C# Syntax:
protected object MemberwiseClone();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: Not()
Summary
Inverts all the bit values in the current BitArray, so that elements set to true are changed to false, and elements set to false are changed to true.
C# Syntax:
public BitArray Not();
Return Value:
The current instance with inverted bit values.
Example
The following example shows how to apply NOT to a BitArray.
 using System;
 using System.Collections;
 public class SamplesBitArray  {
 
    public static void Main()  {
 
       // Creates and initializes two BitArrays of the same size.
       BitArray myBA1 = new BitArray( 4 );
       BitArray myBA2 = new BitArray( 4 );
       myBA1[0] = myBA1[1] = false;
       myBA1[2] = myBA1[3] = true;
       myBA2[0] = myBA2[2] = false;
       myBA2[1] = myBA2[3] = true;
 
       // Performs a bitwise NOT operation between BitArray instances of the same size.
       Console.WriteLine( "Initial values" );
       Console.Write( "myBA1:" );
       PrintValues( myBA1, 8 );
       Console.Write( "myBA2:" );
       PrintValues( myBA2, 8 );
       Console.WriteLine();
 
       myBA1.Not();
       myBA2.Not();
 
       Console.WriteLine( "After NOT" );
       Console.Write( "myBA1:" );
       PrintValues( myBA1, 8 );
       Console.Write( "myBA2:" );
       PrintValues( myBA2, 8 );
       Console.WriteLine();
    }
 
 
    public static void PrintValues( IEnumerable myList, int myWidth )  {
       System.Collections.IEnumerator myEnumerator = myList.GetEnumerator();
       int i = myWidth;
       while ( myEnumerator.MoveNext() )  {
          if ( i <= 0 )  {
             i = myWidth;
             Console.WriteLine();
          }
          i--;
          Console.Write( "\t{0}", myEnumerator.Current );
       }
       Console.WriteLine();
    }
 }
 /* 
 This code produces the following output.
 
 Initial values
 myBA1:    False    False    True    True
 myBA2:    False    True    False    True
 
 After NOT
 myBA1:    True    True    False    False
 myBA2:    True    False    True    False
 */ 

    

Return to top


Method: Or(
   BitArray value
)
Summary
Performs the bitwise OR operation on the elements in the current BitArray against the corresponding elements in the specified BitArray.
C# Syntax:
public BitArray Or(
   BitArray value
);
Parameters:

value

The BitArray with which to perform the bitwise OR operation.

Return Value:
A BitArray containing the result of the bitwise OR operation on the elements in the current BitArray against the corresponding elements in the specified BitArray.
Exceptions
Exception Type Condition
ArgumentNullException value is null.
ArgumentException value and the current BitArray do not have the same number of elements.
Remarks
The bitwise OR operation returns true if one or both operands are true, and returns false if both operands are false.
Example
The following example shows how to apply OR to two BitArray instances.
 using System;
 using System.Collections;
 public class SamplesBitArray  {
 
    public static void Main()  {
 
       // Creates and initializes two BitArrays of the same size.
       BitArray myBA1 = new BitArray( 4 );
       BitArray myBA2 = new BitArray( 4 );
       myBA1[0] = myBA1[1] = false;
       myBA1[2] = myBA1[3] = true;
       myBA2[0] = myBA2[2] = false;
       myBA2[1] = myBA2[3] = true;
 
       // Performs a bitwise OR operation between BitArray instances of the same size.
       Console.WriteLine( "Initial values" );
       Console.Write( "myBA1:" );
       PrintValues( myBA1, 8 );
       Console.Write( "myBA2:" );
       PrintValues( myBA2, 8 );
       Console.WriteLine();
 
       Console.WriteLine( "Result" );
       Console.Write( "OR:" );
       PrintValues( myBA1.Or( myBA2 ), 8 );
       Console.WriteLine();
 
       Console.WriteLine( "After OR" );
       Console.Write( "myBA1:" );
       PrintValues( myBA1, 8 );
       Console.Write( "myBA2:" );
       PrintValues( myBA2, 8 );
       Console.WriteLine();
 
       // Performing OR between BitArray instances of different sizes returns an exception.
       try  {
          BitArray myBA3 = new BitArray( 8 );
          myBA3[0] = myBA3[1] = myBA3[2] = myBA3[3] = false;
          myBA3[4] = myBA3[5] = myBA3[6] = myBA3[7] = true;
          myBA1.Or( myBA3 );
       } catch ( Exception myException )  {
          Console.WriteLine("Exception: " + myException.ToString());
       }
    }
 
 
    public static void PrintValues( IEnumerable myList, int myWidth )  {
       System.Collections.IEnumerator myEnumerator = myList.GetEnumerator();
       int i = myWidth;
       while ( myEnumerator.MoveNext() )  {
          if ( i <= 0 )  {
             i = myWidth;
             Console.WriteLine();
          }
          i--;
          Console.Write( "\t{0}", myEnumerator.Current );
       }
       Console.WriteLine();
    }
 }
 /* 
 This code produces the following output.
 
 Initial values
 myBA1:    False    False    True    True
 myBA2:    False    True    False    True
 
 Result
 OR:    False    True    True    True
 
 After OR
 myBA1:    False    True    True    True
 myBA2:    False    True    False    True
 
 Exception: System.ArgumentException: Array lengths must be the same.
    at System.Collections.BitArray.Or(BitArray value) in <UnknownName>:line 0
    at SamplesBitArray.Main()
 */ 

    

Return to top


Method: Set(
   int index,
   bool value
)
Summary
Sets the bit at a specific position in the BitArray to the specified value.
C# Syntax:
public void Set(
   int index,
   bool value
);
Parameters:

index

The zero-based index of the bit to set.

value

The Boolean value to assign to the bit.

Exceptions
Exception Type Condition
ArgumentOutOfRangeException index is less than zero.

-or-

index is greater than or equal to the number of elements in the BitArray.

Example
The following example shows how to set and get specific elements in a BitArray.
 using System;
 using System.Collections;
 public class SamplesBitArray  {
 
    public static void Main()  {
 
       // Creates and initializes a BitArray.
       BitArray myBA = new BitArray( 5 );
 
       // Displays the properties and values of the BitArray.
       Console.WriteLine( "myBA values:" );
       PrintIndexAndValues( myBA );
 
       // Sets all the elements to true.
       myBA.SetAll( true );
 
       // Displays the properties and values of the BitArray.
       Console.WriteLine( "After setting all elements to true," );
       PrintIndexAndValues( myBA );
 
       // Sets the last index to false.
       myBA.Set( myBA.Count - 1, false );
 
       // Displays the properties and values of the BitArray.
       Console.WriteLine( "After setting the last element to false," );
       PrintIndexAndValues( myBA );
 
       // Gets the value of the last two elements.
       Console.WriteLine( "The last two elements are: " );
       Console.WriteLine( "\tat index {0} : {1}", myBA.Count - 2, myBA.Get( myBA.Count - 2 ) );
       Console.WriteLine( "\tat index {0} : {1}", myBA.Count - 1, myBA.Get( myBA.Count - 1 ) );
    }
 
 
    public static void PrintIndexAndValues( IEnumerable myList )  {
       int i = 0;
       System.Collections.IEnumerator myEnumerator = myList.GetEnumerator();
       while ( myEnumerator.MoveNext() )
          Console.WriteLine( "\t[{0}]:\t{1}", i++, myEnumerator.Current );
       Console.WriteLine();
    }
 }
 /* 
 This code produces the following output.
 
 myBA values:
     [0]:    False
     [1]:    False
     [2]:    False
     [3]:    False
     [4]:    False
 
 After setting all elements to true,
     [0]:    True
     [1]:    True
     [2]:    True
     [3]:    True
     [4]:    True
 
 After setting the last element to false,
     [0]:    True
     [1]:    True
     [2]:    True
     [3]:    True
     [4]:    False
 
 The last two elements are: 
     at index 3 : True
     at index 4 : False
 */ 

    

Return to top


Method: SetAll(
   bool value
)
Summary
Sets all bits in the BitArray to the specified value.
C# Syntax:
public void SetAll(
   bool value
);
Parameters:

value

The Boolean value to assign to all bits.

Example
The following example shows how to set and get specific elements in a BitArray.
 using System;
 using System.Collections;
 public class SamplesBitArray  {
 
    public static void Main()  {
 
       // Creates and initializes a BitArray.
       BitArray myBA = new BitArray( 5 );
 
       // Displays the properties and values of the BitArray.
       Console.WriteLine( "myBA values:" );
       PrintIndexAndValues( myBA );
 
       // Sets all the elements to true.
       myBA.SetAll( true );
 
       // Displays the properties and values of the BitArray.
       Console.WriteLine( "After setting all elements to true," );
       PrintIndexAndValues( myBA );
 
       // Sets the last index to false.
       myBA.Set( myBA.Count - 1, false );
 
       // Displays the properties and values of the BitArray.
       Console.WriteLine( "After setting the last element to false," );
       PrintIndexAndValues( myBA );
 
       // Gets the value of the last two elements.
       Console.WriteLine( "The last two elements are: " );
       Console.WriteLine( "\tat index {0} : {1}", myBA.Count - 2, myBA.Get( myBA.Count - 2 ) );
       Console.WriteLine( "\tat index {0} : {1}", myBA.Count - 1, myBA.Get( myBA.Count - 1 ) );
    }
 
 
    public static void PrintIndexAndValues( IEnumerable myList )  {
       int i = 0;
       System.Collections.IEnumerator myEnumerator = myList.GetEnumerator();
       while ( myEnumerator.MoveNext() )
          Console.WriteLine( "\t[{0}]:\t{1}", i++, myEnumerator.Current );
       Console.WriteLine();
    }
 }
 /* 
 This code produces the following output.
 
 myBA values:
     [0]:    False
     [1]:    False
     [2]:    False
     [3]:    False
     [4]:    False
 
 After setting all elements to true,
     [0]:    True
     [1]:    True
     [2]:    True
     [3]:    True
     [4]:    True
 
 After setting the last element to false,
     [0]:    True
     [1]:    True
     [2]:    True
     [3]:    True
     [4]:    False
 
 The last two elements are: 
     at index 3 : True
     at index 4 : False
 */ 

    

Return to top


Method: ToString()
Inherited
See base class member description: System.Object.ToString
C# Syntax:
public virtual string ToString();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: Xor(
   BitArray value
)
Summary
Performs the bitwise eXclusive OR operation on the elements in the current BitArray against the corresponding elements in the specified BitArray.
C# Syntax:
public BitArray Xor(
   BitArray value
);
Parameters:

value

The BitArray with which to perform the bitwise eXclusive OR operation.

Return Value:
A BitArray containing the result of the bitwise eXclusive OR operation on the elements in the current BitArray against the corresponding elements in the specified BitArray.
Exceptions
Exception Type Condition
ArgumentNullException value is null.
ArgumentException value and the current BitArray do not have the same number of elements.
Remarks
The bitwise exclusive OR operation returns true if exactly one operand is true, and returns false if both operands have the same Boolean value.
Example
The following example shows how to apply XOR to two BitArray instances.
 using System;
 using System.Collections;
 public class SamplesBitArray  {
 
    public static void Main()  {
 
       // Creates and initializes two BitArrays of the same size.
       BitArray myBA1 = new BitArray( 4 );
       BitArray myBA2 = new BitArray( 4 );
       myBA1[0] = myBA1[1] = false;
       myBA1[2] = myBA1[3] = true;
       myBA2[0] = myBA2[2] = false;
       myBA2[1] = myBA2[3] = true;
 
       // Performs a bitwise XOR operation between BitArray instances of the same size.
       Console.WriteLine( "Initial values" );
       Console.Write( "myBA1:" );
       PrintValues( myBA1, 8 );
       Console.Write( "myBA2:" );
       PrintValues( myBA2, 8 );
       Console.WriteLine();
 
       Console.WriteLine( "Result" );
       Console.Write( "XOR:" );
       PrintValues( myBA1.Xor( myBA2 ), 8 );
       Console.WriteLine();
 
       Console.WriteLine( "After XOR" );
       Console.Write( "myBA1:" );
       PrintValues( myBA1, 8 );
       Console.Write( "myBA2:" );
       PrintValues( myBA2, 8 );
       Console.WriteLine();
 
       // Performing XOR between BitArray instances of different sizes returns an exception.
       try  {
          BitArray myBA3 = new BitArray( 8 );
          myBA3[0] = myBA3[1] = myBA3[2] = myBA3[3] = false;
          myBA3[4] = myBA3[5] = myBA3[6] = myBA3[7] = true;
          myBA1.Xor( myBA3 );
       } catch ( Exception myException )  {
          Console.WriteLine("Exception: " + myException.ToString());
       }
    }
 
 
    public static void PrintValues( IEnumerable myList, int myWidth )  {
       System.Collections.IEnumerator myEnumerator = myList.GetEnumerator();
       int i = myWidth;
       while ( myEnumerator.MoveNext() )  {
          if ( i <= 0 )  {
             i = myWidth;
             Console.WriteLine();
          }
          i--;
          Console.Write( "\t{0}", myEnumerator.Current );
       }
       Console.WriteLine();
    }
 }
 /* 
 This code produces the following output.
 
 Initial values
 myBA1:    False    False    True    True
 myBA2:    False    True    False    True
 
 Result
 XOR:    False    True    True    False
 
 After XOR
 myBA1:    False    True    True    False
 myBA2:    False    True    False    True
 
 Exception: System.ArgumentException: Array lengths must be the same.
    at System.Collections.BitArray.Xor(BitArray value) in <UnknownName>:line 0
    at SamplesBitArray.Main()
 */ 

    

Return to top


Top of page

Copyright (c) 2002 Microsoft Corporation. All rights reserved.