Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use Object Initializers on a bool?

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

like image 304
AngryHacker Avatar asked Dec 09 '22 17:12

AngryHacker


2 Answers

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);
like image 67
Lee Avatar answered Dec 25 '22 05:12

Lee


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

like image 37
Mark Byers Avatar answered Dec 25 '22 05:12

Mark Byers