To start, we allocate and initialize bool arrays. The syntax is the same as other arrays, in that you need to specify the array length inside the square brackets.
Tip When you allocate the bool array, its values are filled with False. You do not need to initialize any values to False in your code.
Info You should initialize values to True as required. You can loop over bool arrays with foreach or with for.
using System;
// Initialize new bool array.
bool[] array = new bool[10];
array[0] = false;
array[1] = true;
array[2] = false;
array[3] = true;
// Loop through all values.
foreach (bool value in array)
{
Console.WriteLine(value);
}False
True
False
True
False
False
False
False
False
False
Memory. The bool value can be expressed with a single bit in memory—one means true and zero means false. However, the bool type in C# is expressed in eight bits, or one byte.
Info We look at a program that allocates one million bools. This results in 1,000,012 bytes being allocated.
However One million bits is only 125,000 bytes. So a bool array representation is less efficient.
using System;
//// Initialize new bool array.//
bool[] array = new bool[1000000];
//// Initialize each other value to true.//
for (int i = 0; i < array.Length; i += 2)
{
array[i] = true;
}Size of the array in memory: 1,000,012 bytes [CLRProfiler].
Each bool requires 1 byte.
Array reference requires 12 bytes.
Sorting bool arrays is useful for certain algorithms. It can help methods that favor some object, but do not want to remove objects.
Arguments. As with other arrays, you can pass bool arrays as arguments by using the bool[] type for the parameter. You can also return bool arrays from methods with the same type.
Tip Due to the extra address space required for booleans, it is better to use BitArray when you have trillions of values.
BitArray. There is a BitArray class in the System.Collections namespace. This is more compact than bool arrays, and can reduce memory usage.
Summary. The program showed that elements in bool arrays are initialized to false automatically. We saw that bool arrays require one byte for each element.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Dec 19, 2023 (grammar).