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
Number of elements contained in the BitArray in C#?
The Count property in C# is used to get the number of elements contained in a BitArray. This property returns an integer value representing the total number of bits in the BitArray, regardless of their values (true or false).
Syntax
Following is the syntax for accessing the Count property −
int count = bitArray.Count;
Return Value
The Count property returns an int value representing the total number of elements (bits) in the BitArray.
Using Count Property with BitArray Operations
The following example demonstrates how to use the Count property with BitArray operations −
using System;
using System.Collections;
public class Demo {
public static void Main() {
BitArray arr1 = new BitArray(5);
BitArray arr2 = new BitArray(5);
arr1[0] = false;
arr1[1] = false;
arr2[0] = false;
arr2[1] = true;
Console.WriteLine("BitArray1 elements...");
foreach (bool res in arr1) {
Console.WriteLine(res);
}
Console.WriteLine("\nBitArray2 elements...");
foreach (bool res in arr2) {
Console.WriteLine(res);
}
Console.WriteLine("\nBitwise OR operation...");
IEnumerable demoEnum = arr1.Or(arr2);
foreach(Object ob in demoEnum) {
Console.WriteLine(ob);
}
Console.WriteLine("\nNumber of elements in the resultant BitArray = " + arr1.Count);
}
}
The output of the above code is −
BitArray1 elements... False False False False False BitArray2 elements... False True False False False Bitwise OR operation... False True False False False Number of elements in the resultant BitArray = 5
Using Count with CopyTo Method
The Count property is useful when copying elements from BitArray to other arrays −
using System;
using System.Collections;
public class Demo {
public static void Main() {
BitArray arr = new BitArray(2);
arr[0] = false;
arr[1] = true;
Console.WriteLine("Elements in BitArray...");
foreach (bool res in arr) {
Console.WriteLine(res);
}
Console.WriteLine("\nNumber of elements in the BitArray = " + arr.Count);
bool[] boolArr = new bool[arr.Count];
boolArr[0] = true;
boolArr[1] = false;
arr.CopyTo(boolArr, 0);
Console.WriteLine("\nArray after copying BitArray...");
foreach(Object obj in boolArr) {
Console.WriteLine(obj);
}
}
}
The output of the above code is −
Elements in BitArray... False True Number of elements in the BitArray = 2 Array after copying BitArray... False True
Conclusion
The Count property provides an efficient way to determine the number of elements in a BitArray. This property is particularly useful when performing operations like copying elements to other arrays or iterating through specific ranges of the BitArray.
