views:

75

answers:

3

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

+3  A: 

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
With the initializer method, though, this doesn't allow you to pass in the size of the array
Michael Haren
`weeks` is actually a variable. I don't know ahead of time what the value will be. I should have made it clearer.
AngryHacker
+8  A: 

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
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
+2  A: 

This should be what you are looking for:

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