Setting entire bool[] to false

66,373

Solution 1

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

bool[] switches = new bool[20];

Solution 2

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();

Solution 3

You can try Array.Clear as an alternative:

Array.Clear(switches, 0, switches.Length);

Not sure what the relative performance will be, but you should definitely not expect miracles.

Solution 4

I believe the default value of a boolean is false. However as a sanity check, it makes sense to iterate through it. AFAIK, that is the fastest way

See: How to populate/instantiate a C# array with a single value?

Solution 5

Is there a better way to set the entire bool array to false?

No, there is not.

You could benchmark, if assigning a new array is faster, but I doubt it. Of course, this would be done as pointed out by Adam Houldsworth.

switches = new bool[20];
Share:
66,373
JMC17
Author by

JMC17

Updated on April 19, 2020

Comments

  • JMC17
    JMC17 about 4 years

    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?