Is it possible to do the following (e.g. initialize bool array and set all elements to true) in one line using object initializers?
int weeks = 5;
bool[] weekSelected = new bool[weeks];
for (int i = 0; i < weeks; i++)
{
weekSelected[i] = true;
}
I can't quite get it to work.
Edit: I should have mentioned that I am using VS2008 with .NET 2.0 (so Enumerable won't work).
bool[] weekSelected = Enumerable.Range(0, 5).Select(i => true).ToArray();
EDIT: If you can't use enumerable, you might be able to use a BitArray:
BitArray bits = new BitArray(count, true);
and then copy to an array as needed:
bool[] array = new bool[count];
bits.CopyTo(array, 0);
If you're using .NET 2.0, using a loop is the right way to do it. I wouldn't change it.
Original answer.
Your type declaration is wrong. Try this:
bool[] weekSelected = new bool[] { true, true, true, true, true };
You can also do this to avoid repeating yourself:
bool[] weekSelected = Enumerable.Repeat(true, 5).ToArray();
Note that this is not as efficient as a loop, but if you have say 100 values and performance is not critical, it's more concise than the loop and less typing than { true, true, true, ... }
.
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