How to create a shallow copy of the BitArray in C#?

CsharpServer Side ProgrammingProgramming

To create a shallow copy of the BitArray, the code is as follows −

Example

 Live Demo

using System;
using System.Collections;
public class Demo {
   public static void Main(){
      BitArray arr1 = new BitArray(5);
      arr1[0] = false;
      arr1[1] = true;
      Console.WriteLine("BitArray length = "+arr1.Length);
      Console.WriteLine("BitArray first element = "+arr1.Get(0));
      Console.WriteLine("BitArray second element = "+arr1.Get(1));
      BitArray arr2 = (BitArray)arr1.Clone();
      Console.WriteLine("\nBitArray2 length = "+arr2.Length);
      Console.WriteLine("BitArray2 first element = "+arr2.Get(0));
      Console.WriteLine("BitArray2 second element = "+arr2.Get(1));
   }
}

Output

This will produce the following output −

BitArray length = 5
BitArray first element = False
BitArray second element = True

BitArray2 length = 5
BitArray2 first element = False
BitArray2 second element = Tru

Example

Let us now see another example −

 Live Demo

using System;
using System.Collections;
public class Demo {
   public static void Main(){
      BitArray arr1 = new BitArray(5);
      arr1[0] = false;
      arr1[1] = true;
      arr1[2] = false;
      arr1[3] = true;
      arr1[3] = true;
      Console.WriteLine("BitArray length = "+arr1.Length);
      Console.WriteLine("Elements in BitArray1...");
      foreach(Object obj in arr1)
         Console.WriteLine(obj);
      BitArray arr2 = (BitArray)arr1.Clone();
      Console.WriteLine("\nBitArray2 length = "+arr1.Length);
      Console.WriteLine("Elements in BitArray2...");
      foreach(Object obj in arr2)
         Console.WriteLine(obj);
   }
}

Output

This will produce the following output −

BitArray length = 5
Elements in BitArray1...
False
True
False
True
False

BitArray2 length = 5
Elements in BitArray2...
False
True
False
True
False
raja
Published on 10-Dec-2019 10:58:02
Advertisements