4

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).

ICR
  • 13,896
  • 4
  • 50
  • 78
AngryHacker
  • 59,598
  • 102
  • 325
  • 594
  • 1
    Besides that the code doesn't work in current form you do have a typo, second line should be: bool[] weekSelected... – thelsdj Feb 26 '10 at 22:52

3 Answers3

9

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);
Lee
  • 142,018
  • 20
  • 234
  • 287
  • That's a great answers, but I am using .NET 2.0 with VS2008, so Enumerable does not exist there. I updated the question. – AngryHacker Feb 26 '10 at 22:48
3

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, ... }.

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
2

This should be what you are looking for:

bool[] weekSelected = Enumerable.Repeat<bool>(true, weeks).ToArray();
AxelEckenberger
  • 16,628
  • 3
  • 48
  • 70