Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Set all bits in the BitArray to the specified value in C#
The BitArray.SetAll() method in C# is used to set all bits in the BitArray to a specified boolean value. This method provides an efficient way to initialize or reset all elements in a BitArray with a single operation, rather than setting each bit individually.
Syntax
Following is the syntax for the SetAll() method −
public void SetAll(bool value)
Parameters
value: A boolean value (true or false) to assign to all bits in the BitArray.
Using SetAll() to Set All Bits to True
The following example demonstrates setting all bits in a BitArray to true −
using System;
using System.Collections;
public class Demo {
public static void Main() {
BitArray arr = new BitArray(5);
arr[0] = false;
arr[1] = false;
arr[2] = false;
arr[3] = false;
Console.WriteLine("BitArray...");
foreach(Object ob in arr) {
Console.WriteLine(ob);
}
arr.SetAll(true);
Console.WriteLine("\nUpdated BitArray...");
foreach(Object ob in arr) {
Console.WriteLine(ob);
}
}
}
The output of the above code is −
BitArray... False False False False False Updated BitArray... True True True True True
Using SetAll() to Set All Bits to False
The following example demonstrates setting all bits in a BitArray to false −
using System;
using System.Collections;
public class Demo {
public static void Main() {
BitArray arr = new BitArray(5);
arr[0] = true;
arr[1] = false;
arr[2] = true;
arr[3] = false;
Console.WriteLine("BitArray...");
foreach(Object ob in arr) {
Console.WriteLine(ob);
}
arr.SetAll(false);
Console.WriteLine("\nUpdated BitArray...");
foreach(Object ob in arr) {
Console.WriteLine(ob);
}
}
}
The output of the above code is −
BitArray... True False True False False Updated BitArray... False False False False False
Practical Example with Boolean Operations
Here's a more practical example showing how SetAll() can be used for bulk operations −
using System;
using System.Collections;
public class Demo {
public static void Main() {
BitArray flags = new BitArray(8);
Console.WriteLine("Initial BitArray (all false by default):");
PrintBitArray(flags);
// Enable all flags
flags.SetAll(true);
Console.WriteLine("\nAfter SetAll(true):");
PrintBitArray(flags);
// Reset all flags
flags.SetAll(false);
Console.WriteLine("\nAfter SetAll(false):");
PrintBitArray(flags);
}
static void PrintBitArray(BitArray arr) {
for(int i = 0; i
The output of the above code is −
Initial BitArray (all false by default):
00000000
After SetAll(true):
11111111
After SetAll(false):
00000000
Conclusion
The SetAll() method provides an efficient way to set all bits in a BitArray to the same value with a single method call. It's particularly useful for initialization, resetting flags, or performing bulk operations on BitArray collections.
