C# | How to create a shallow copy of the BitArray
BitArray.Clone Method is used to create a shallow copy of the BitArray. This method only copies 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.
public object Clone ();
Example 1: Here we create an array of type byte. Then declare an object B1 of type BitArray and initialize it using the byte array created before. Declare another object B2 of type BitArray which will be used to store the clone of B1. The instruction B1.Clone returns the shallow copy of B1, which is of type System.Collections. Therefore explicitly convert it to BitArray before storing it in B2 object. And finally, display the cloned BitArray.
Length of B2: 16 B2 Contains: True False False False False False False False True True False False False False False False
Example 2: A shallow copy only copies the contents of the BitArray and not the object references, any changes made to B2 will only update those changes in B2 and not in B1.
B2 Before Making any changes: True False True False B2 After changes: False True True False B1 After Changes: True False True False