C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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.
ForeachForC# program that uses bool array
using System;
class Program
{
static void Main()
{
//
// Initialize new bool array.
//
bool[] array = new bool[10];
array[0] = false; // <-- Not needed
array[1] = true;
array[2] = false; // <-- Not needed
array[3] = true;
//
// Loop through all values.
//
foreach (bool value in array)
{
Console.WriteLine(value);
}
}
}
Output
False
True
False
True
False
False
False
False
False
False
And: To prove this, 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.
C# program that allocates bool array
using System;
class Program
{
static void Main()
{
//
// 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;
}
}
}
Notes:
Size of the array in memory: 1,000,012 bytes [CLRProfiler].
Each bool requires 1 byte.
Array reference requires 12 bytes.
Tip: Due to the extra address space required for booleans, it is better to use BitArray when you have trillions of values.