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?
Just assign it to a new array: switches = new bool[20] , by default all items will be false.
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.
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] = {};
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.
default(bool)
is false
, just create the array and each element will be false
.
bool[] switches = new bool[20];
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With