Array Of Bools

Hello, I was wondering if it was possible to hold an array of booleans and then be able to check if they are false or not in C#. What i wanted to do is have an if statement that says if there all false, then set one true. The thing is im not very familiar with arrays so can someone point me in the right direction for what im looking for?

Thanks For The Help :slight_smile:

just use a for loop:

bool allFalse = true;
bool[] array;
for(int i = 0; i < array.length; i++)
  if(!allFalse) break; // allow the loop to end premature
  else allFalse = ! array*;*

if(allFalse)
array[0] = true;
is that what you want to do?

This is quite a good tutorial for arrays in C#. See if it helps you.

MSND C# Tutorial

The easiest thing to do is use LINQ. (using System.Linq; at the top of your code):

bool[] array;
if (array.All(b => !b)) //do whatever

You can use one of a couple of methods in the System.Array class: !Array.Exists(array, item => item) or Array.TrueForAll(array, item => !item). Alternatively, if you put using System.Linq; at the top of the file, then you can use either array.All(item => !item) or !array.Any(item => item).

The list of booleans more compactly as a BitArray object (defined in the System.Collections namespace), in which case either of those last two methods may be used; just replace the array with bitArray.Cast<bool>().

However, if you don’t need to store more than 32 values in the list, then you can achieve greater efficiency by scrapping the use of an actual array completely and instead using an instance of the BitVector32 structure (in the System.Collections.Specialized namespace); this enables replacing the whole loop with a single constant-time statement:

allFalse = (bitVector.Data == 0);

In this case, if you need to store fewer than 32 values, then you might need an extra variable to store the logical count of booleans.