Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting entire bool[] to false [duplicate]

I'm already aware of the loop example below

bool[] switches = new bool[20]; for (int i = 0; i < switches.Length; i++) { switches[i] = false; } 

But is there a more efficient way to set the entire array to false?

To explain myself a bit, i'm not, like the example above, setting a new bool array to false as it would already be false anyway. In my case i'm reading a large portion of a process memory which could fire about 18724 times at most as it is searching for patterns. When it determines that the current bytes doesn't contain the pattern, it sets the entire bool array to false along with a few other things then reads the next memory block and restarts the loop.

Although its more out of curiosity that I asked this question because the whole process still takes less than a second.

So again, my question is, is there a better way to set the entire bool array to false?

like image 1000
JMC17 Avatar asked Dec 13 '13 11:12

JMC17


People also ask

How do you set a boolean array to false?

Just assign it to a new array: switches = new bool[20] , by default all items will be false.

How do you initialize a boolean array to true?

An array of booleans are initialized to false and arrays of reference types are initialized to null. In some cases, we need to initialize all values of the boolean array with true or false. We can use the Arrays. fill() method in such cases.

How do you initialize a boolean array in C++?

in guaranteed to initialize the whole array with null-pointers of type char * . bool myBoolArray[ARRAY_SIZE] = { false }; char* myPtrArray[ARRAY_SIZE] = { nullptr }; but the point is that = { 0 } variant gives you exactly the same result. T myArray[ARRAY_SIZE] = {};

How to get bool value in c#?

Syntax: public bool Equals (bool obj); Here, obj is a boolean value to compare to this instance. Return Value: This method returns true if obj has the same value as this instance otherwise it returns false.


2 Answers

default(bool) is false, just create the array and each element will be false.

bool[] switches = new bool[20]; 
like image 198
Felipe Oriani Avatar answered Sep 27 '22 19:09

Felipe Oriani


If you can re-init array, then answer of Fabian Bigler is the right way to go.

If, however, you want to re-init it to true, then use Enumerable.Repeat:

switches = Enumerable.Repeat(true, 20).ToArray(); 
like image 24
Sinatr Avatar answered Sep 27 '22 19:09

Sinatr