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.
Syntax:
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.
csharp
using System;
using System.Collections;
class GFG {
static void Main( string [] args)
{
byte [] ByteArray = new byte [] {1, 3};
BitArray B1 = new BitArray(ByteArray);
BitArray B2 = new BitArray(4);
B2 = (BitArray)B1.Clone();
Console.WriteLine( "Length of B2: {0}" , B2.Length);
Console.WriteLine( "\nB2 Contains:" );
foreach (Object item in B2)
{
Console.WriteLine(item);
}
}
}
|
Output:
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.
csharp
using System;
using System.Collections;
class GFG {
static void Main( string [] args)
{
bool [] BooleanArray = new bool [] { true ,
false , true , false };
BitArray B1 = new BitArray(BooleanArray);
int i;
BitArray B2 = new BitArray(4);
B2 = (BitArray)B1.Clone();
i = 4;
Console.WriteLine( "B2 Before Making any changes:" );
foreach (Object item in B2)
{
if (i <= 0)
{
Console.WriteLine();
i = 6;
}
i--;
Console.Write( "{0, 4} " , item);
}
B2[0] = false ;
B2[1] = true ;
i = 4;
Console.WriteLine( "\n\nB2 After changes:" );
foreach (Object item in B2)
{
if (i <= 0)
{
Console.WriteLine();
i = 6;
}
i--;
Console.Write( "{0, 4} " , item);
}
Console.WriteLine( "\n\nB1 After Changes:" );
i = 4;
foreach (Object item in B1)
{
if (i <= 0)
{
Console.WriteLine();
i = 6;
}
i--;
Console.Write( "{0, 4} " , item);
}
}
}
|
Output:
B2 Before Making any changes:
True False True False
B2 After changes:
False True True False
B1 After Changes:
True False True False
Reference:
Last Updated :
16 Jul, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...