Can i use Object Initializers on a bool?

Is it possible to do the following (for example, initialize the bool array and set all elements to true) on the same line using object initializers?

int weeks = 5; bool[] weekSelected = new bool[weeks]; for (int i = 0; i < weeks; i++) { weekSelected[i] = true; } 

I can not make it work.


Edit: I should have mentioned that I am using VS2008 with .NET 2.0 (so Enumerable will not work).

+4
source share
3 answers

bool[] weekSelected = Enumerable.Range(0, 5).Select(i => true).ToArray();

EDIT: if you cannot use an enumeration, you can use a BitArray :

 BitArray bits = new BitArray(count, true); 

and then copy to the array as needed:

 bool[] array = new bool[count]; bits.CopyTo(array, 0); 
+9
source

If you are using .NET 2.0, using a loop is the right way to do this. I would not change it.


The original answer.

Your ad type is incorrect. Try the following:

 bool[] weekSelected = new bool[] { true, true, true, true, true }; 

You can also do this so as not to repeat yourself:

 bool[] weekSelected = Enumerable.Repeat(true, 5).ToArray(); 

Please note that this is not as efficient as the loop, but if you say that 100 values ​​and performance are not critical, it is shorter than the loop and takes less text than { true, true, true, ... } .

+3
source

This should be what you are looking for:

 bool[] weekSelected = Enumerable.Repeat<bool>(true, weeks).ToArray(); 
+2
source

Source: https://habr.com/ru/post/1302541/


All Articles