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
What is the Item property of BitArray class in C#?
The Item property of the BitArray class in C# gets or sets the value of the bit at a specific position in the BitArray. This property acts as an indexer, allowing you to access individual bits using bracket notation like bitArray[index].
The Item property provides a convenient way to read and modify individual bits without having to use explicit method calls. It returns a bool value representing the bit state at the specified index.
Syntax
Following is the syntax for accessing the Item property −
public bool this[int index] { get; set; }
To access or modify a bit −
bool value = bitArray[index]; // Get bit value bitArray[index] = true; // Set bit value
Parameters
index − The zero-based index of the bit to get or set. Must be within the bounds of the BitArray.
Return Value
Returns a bool value representing the bit at the specified position. true indicates the bit is set (1), and false indicates the bit is unset (0).
Using Item Property to Access Bits
Example
using System;
using System.Collections;
class Demo {
static void Main() {
bool[] arr = new bool[5];
arr[0] = true;
arr[1] = true;
arr[2] = false;
arr[3] = false;
arr[4] = true;
BitArray bitArr = new BitArray(arr);
Console.WriteLine("BitArray contents:");
foreach (bool b in bitArr) {
Console.WriteLine(b);
}
// Using Item property to access specific bits
bool secondBit = bitArr[1];
Console.WriteLine("Value of 2nd element: " + secondBit);
bool lastBit = bitArr[4];
Console.WriteLine("Value of 5th element: " + lastBit);
}
}
The output of the above code is −
BitArray contents: True True False False True Value of 2nd element: True Value of 5th element: True
Using Item Property to Modify Bits
Example
using System;
using System.Collections;
class Demo {
static void Main() {
BitArray bitArr = new BitArray(4, false);
Console.WriteLine("Initial BitArray:");
PrintBitArray(bitArr);
// Set specific bits using Item property
bitArr[0] = true;
bitArr[2] = true;
Console.WriteLine("After setting bits 0 and 2:");
PrintBitArray(bitArr);
// Modify existing bit
bitArr[0] = false;
Console.WriteLine("After setting bit 0 to false:");
PrintBitArray(bitArr);
}
static void PrintBitArray(BitArray arr) {
for (int i = 0; i < arr.Length; i++) {
Console.Write(arr[i] ? "1 " : "0 ");
}
Console.WriteLine();
}
}
The output of the above code is −
Initial BitArray: 0 0 0 0 After setting bits 0 and 2: 1 0 1 0 After setting bit 0 to false: 0 0 1 0
Conclusion
The Item property of BitArray provides indexed access to individual bits using familiar bracket notation. It allows both reading and writing bit values at specific positions, making BitArray manipulation intuitive and efficient for bit-level operations.
