Open In App

C# | Copying BitArray elements to an Array

The BitArray class manages a compact array of bit values, which are represented as Booleans, where true indicates that the bit is on i.e, 1 and false indicates the bit is off i.e, 0. This class is contained in System.Collections namespace.
BitArray.CopyTo(Array, Int32) method is used to copy the entire BitArray to a compatible one-dimensional Array, starting at the specified index of the target array.

Properties:



Syntax:

public void CopyTo (Array arr, int index);

Parameters:



Exceptions:

Below given are some examples to understand the implementation in a better way:

Example 1:




// C# code to copy BitArray to Array,
// starting at the specified index
// of the target array
using System;
using System.Collections;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a BitArray
        BitArray myBitArr = new BitArray(4);
  
        myBitArr[0] = true;
        myBitArr[1] = true;
        myBitArr[2] = true;
        myBitArr[3] = true;
  
        // Creating a bool array
        bool[] myBoolArr = new bool[8];
  
        myBoolArr[0] = false;
        myBoolArr[1] = false;
  
        // Copying BitArray to Array,
        // starting at the specified index
        // of the target array
        myBitArr.CopyTo(myBoolArr, 3);
  
        // Displaying elements in myBoolArr
        foreach(Object obj in myBoolArr)
        {
            Console.WriteLine(obj);
        }
    }
}

Output:

False
False
False
True
True
True
True
False

Example 2:




// C# code to copy BitArray to Array,
// starting at the specified index
// of the target array
using System;
using System.Collections;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a BitArray
        BitArray myBitArr = new BitArray(3);
  
        myBitArr[0] = true;
        myBitArr[1] = true;
        myBitArr[2] = true;
  
        // Creating a bool array
        bool[] myBoolArr = new bool[8];
  
        myBoolArr[0] = false;
        myBoolArr[1] = false;
        myBoolArr[2] = false;
  
        // Copying BitArray to Array,
        // starting at the specified index
        // of the target array
        // This should raise "ArgumentOutOfRangeException"
        // as index is less than 0
        myBitArr.CopyTo(myBoolArr, -2);
  
        // Displaying elements in myBoolArr
        foreach(Object obj in myBoolArr)
        {
            Console.WriteLine(obj);
        }
    }
}

Runtime Error:

Unhandled Exception:
System.ArgumentOutOfRangeException: Non-negative number required.
Parameter name: index

Note:

Reference:


Article Tags :
C#