Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C# Data Types
  • C# Decision Making
  • C# Methods
  • C# Delegates
  • C# Constructors
  • C# Arrays
  • C# ArrayList
  • C# String
  • C# Tuple
  • C# Indexers
  • C# Interface
  • C# Multithreading
  • C# Exception
Open In App
Next Article:
C# | Copying BitArray elements to an Array
Next article icon

C# BitArray Class

Last Updated : 31 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

BitArray class in C# is part of the System.Collections namespace. It manages a compact array of bit values, which are represented as Booleans, where true indicates that the bit is on i.e. 1, and false indicates the bit is off i.e. 0. 

  • The BitArray class is a collection class in which the capacity is always the same as the count.
  • Elements are added to a BitArray by increasing the Length property.
  • Elements are deleted by decreasing the Length property.
  • Elements in this collection can be accessed using an integer index. Indexes in this collection are zero-based.

Example: This example demonstrates how to create a BitArray, set individual bits to true, and print the bit value at each index.

C#
using System; using System.Collections;  class Geeks {     static void Main(string[] args)     {         // Creating a BitArray with 5 bits (initialized to         // false by default)         BitArray b = new BitArray(5);          // Setting individual bits         b[0] = true;         b[1] = true;         b[3] = true;          // Printing the BitArray (will display true or false         // for each bit)         for (int i = 0; i < b.Count; i++) {             Console.WriteLine(                 $"Bit at index {i}: {b[i]}");         }     } } 

Output
Bit at index 0: True Bit at index 1: True Bit at index 2: False Bit at index 3: True Bit at index 4: False 

Declaration of BitArray

In C#, the bitArray is declared as:

BitArray bitArray = new BitArray(size);

Constructors

ConstructorDescription
BitArray(BitArray)Initializes a new instance of the BitArray class that contains bit values copied from the specified BitArray.
BitArray(Boolean[])Initializes a new instance of the BitArray class that contains bit values copied from the specified array of Booleans.
BitArray(Byte[])Initializes a new instance of the BitArray class that contains bit values copied from the specified array of bytes.
BitArray(Int32)Initializes a new instance of the BitArray class that can hold the specified number of bit values, which are initially set to false.
BitArray(Int32, Boolean)Initializes a new instance of the BitArray class that can hold the specified number of bit values, which are initially set to the specified value.
BitArray(Int32[])Initializes a new instance of the BitArray class that contains bit values copied from the specified array of 32-bit integers.


Example: This example demonstrates how to create a BitArray, set individual bit values and reterive specific bit values using the Get() method.

C#
// C# Program to get a BitArray  using System;  using System.Collections;   class Geeks {  	public static void Main()  	{   		// Creating a BitArray  		BitArray b = new BitArray(5);   		b[0] = true;  		b[1] = true;  		b[2] = false;  		b[3] = true;  		b[4] = false;   		// To get the value of index at index 2  		Console.WriteLine(b.Get(2));   		// To get the value of index at index 3  		Console.WriteLine(b.Get(3));  	}  }  

Output
False True 

Properties

PropertyDescription
CountGets the number of elements contained in the BitArray.
IsReadOnlyGets a value indicating whether the BitArray is read-only.
IsSynchronizedGets a value indicating whether access to the BitArray is synchronized (thread safe).
Item[Int32]Gets or sets the value of the bit at a specific position in the BitArray.
LengthGets or sets the number of elements in the BitArray.
SyncRootGets an object that can be used to synchronize access to the BitArray.


Example: This example demonstrates checking if a BitArray is read-only using the IsReadOnly property and getting the number of elements using the Count property.

C#
// C# program to demonstrates the  // IsReadOnly and Count property using System;  using System.Collections;   class Geeks {  	 	public static void Main()  	{  	 		// Creating a BitArray  		BitArray b = new BitArray(new byte[] { 0, 0, 0, 1 });  	 		// IsReadOnly Property  		 		// Checking if the BitArray is read-only  		Console.WriteLine(b.IsReadOnly);  		 		// Count Property 		 		// To get the number of elements  		// contained in the BitArray  		Console.WriteLine(b.Count);  		 	}  }  

Output
False 32 

Methods

MethodDescription
And(BitArray)Performs the bitwise AND operation between the elements of the current BitArray object and the corresponding elements in the specified array. The current BitArray object will be modified to store the result of the bitwise AND operation.
Clone()Creates a shallow copy of the BitArray.
CopyTo(Array, Int32)Copies the entire BitArray to a compatible one-dimensional Array, starting at the specified index of the target array.
Equals(Object)Determines whether the specified object is equal to the current object.
Get(Int32)Gets the value of the bit at a specific position in the BitArray.
GetEnumerator()Returns an enumerator that iterates through the BitArray.
LeftShift(Int32)It is used to shift the bits of the bit array to the left by one position and adds zeros on the shifted position.
GetHashCode()Serves as the default hash function.
GetType()Gets the Type of the current instance.
MemberwiseClone()Creates a shallow copy of the current Object.
Not()Inverts all the bit values in the current BitArray, so that elements set to true are changed to false, and elements set to false are changed to true.
RightShift(Int32)It is used to shift the bits of the bit array to the right by one position and adds zeros on the shifted position.
Or(BitArray)Performs the bitwise OR operation between the elements of the current BitArray object and the corresponding elements in the specified array. The current BitArray object will be modified to store the result of the bitwise OR operation.
Set(Int32, Boolean)Sets the bit at a specific position in the BitArray to the specified value.
SetAll(Boolean)Sets all bits in the BitArray to the specified value.
ToString()Returns a string that represents the current object.
Xor(BitArray)Performs the bitwise exclusive OR operation between the elements of the current BitArray object against the corresponding elements in the specified array. The current BitArray object will be modified to store the result of the bitwise exclusive OR operation.


Example 1: This example demonstrates performing a bitwise OR operation between two BitArray objects and printing the resulting bit values.

C#
// C# Program to do bitwise  // OR operation between BitArray  using System;  using System.Collections;   class Geeks {   	public static void Main()  	{   		// Creating a BitArray  		BitArray b1 = new BitArray(4);   		// Creating a BitArray  		BitArray b2 = new BitArray(4);   		// Initializing values in b1  		b1[0] = false;  		b1[1] = false;  		b1[2] = true;  		b1[3] = true;   		// Initializing values in b2  		b2[0] = false;  		b2[2] = false;  		b2[1] = true;  		b2[3] = true;   		// function calling  		PrintValues(b1.Or(b2));  	}   	// Displaying the result  	public static void PrintValues(IEnumerable myList)  	{  		foreach(Object o in myList)  		{  			Console.WriteLine(o);  		}  	}  }  

Output
False True True True 

Example 2: This example demonstrates setting all bits in a BitArray to false using the SetAll() method and printing the bit values before and after.

C#
// C# code to set all bits in the  // BitArray to the specified value  using System; using System.Collections;  class Geeks {      public static void Main()     {          // Creating a BitArray b          BitArray b = new BitArray(5);          // Initializing all the bits in a          b[0] = false;         b[1] = true;         b[2] = true;         b[3] = false;         b[4] = true;          // Printing the values in b          Console.WriteLine("Initially the bits are as: ");          PrintIndexAndValues(b);          // Setting all bits to false          b.SetAll(false);          // Printing the values in b          // It should display all the bits as false          Console.WriteLine("Finally the bits are as: ");          PrintIndexAndValues(b);     }      // Function to display bits      public static void PrintIndexAndValues(IEnumerable myArr)     {         foreach(Object o in myArr)         {             Console.WriteLine(o);         }     } }  

Output
Initially the bits are as:  False True True False True Finally the bits are as:  False False False False False 


Next Article
C# | Copying BitArray elements to an Array

S

Sahil_Bansall
Improve
Article Tags :
  • C#
  • CSharp-Collections-Namespace

Similar Reads

  • C# BitConverter Class
    BitConverter class in C# is used to convert base data types to an array of bytes and vice versa. This class is defined under the System namespace and provides various methods to perform conversions efficiently. It helps in manipulating value types in their raw form, representing them as a sequence o
    4 min read
  • C# Arrays
    An array is a group of like-typed variables that are referred to by a common name. And each data item is called an element of the array. The data types of the elements may be any valid data type like char, int, float, etc. and the elements are stored in a contiguous location. Length of the array spe
    8 min read
  • C# Jagged Arrays
    A jagged array is an array of arrays, where each element in the main array can have a different length. In simpler terms, a jagged array is an array whose elements are themselves arrays. These inner arrays can have different lengths. Can also be mixed with multidimensional arrays. The number of rows
    5 min read
  • C# | Check if the BitArray is read-only
    The BitArray class manages a compact array of bit values, which are represented as Booleans, where true indicates that the bit is on i.e, 1 and false indicates the bit is off i.e, 0. This class is contained in System.Collections namespace. BitArray.IsReadOnly property is used to get a value indicati
    2 min read
  • C# | Copying BitArray elements to an Array
    The BitArray class manages a compact array of bit values, which are represented as Booleans, where true indicates that the bit is on i.e, 1 and false indicates the bit is off i.e, 0. This class is contained in System.Collections namespace. BitArray.CopyTo(Array, Int32) method is used to copy the ent
    3 min read
  • C# | Check if two BitArray objects are equal
    Equals(Object) Method which is inherited from the Object class is used to check if a specified BitArray object is equal to another BitArray object or not. Syntax: public virtual bool Equals (object obj); Here, obj is the object which is to be compared with the current object. Return Value: This meth
    2 min read
  • C# | Inverting all bit values in BitArray
    The BitArray class manages a compact array of bit values, which are represented as Booleans, where true indicates that the bit is on i.e, 1 and false indicates the bit is off i.e, 0. This class is contained in System.Collections namespace. BitArray.Not method inverts all the bit values in the curren
    2 min read
  • BitArray.LeftShift() Method in C# with Examples
    BitArray class manages a array of bit values, which are represented as Booleans, where true indicates bit is 1 and false indicates bit is 0. This class is contained in namespace, System.Collections. BitArray.LeftShift(Int32) method is used to shift the bits of the bit array to the left by one positi
    2 min read
  • BitArray.RightShift() Method in C# with Examples
    BitArray class manages a array of bit values, which are represented as Booleans, where true indicates bit is 1 and false indicates bit is 0. This class is contained in namespace, System.Collections. BitArray.RightShift(Int32) method is used to shift the bits of the bit array to the right by one posi
    2 min read
  • How to create a shallow copy of BitArray in C#
    BitArray.Clone() Method is used to create a shallow copy of the specified BitArray. A shallow copy of a collection copies only the elements of the collection irrespective of reference types or value types. But it does not copy the objects that the references refer to. The references in the new colle
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences