Search code examples
c#visual-studio-2008.net-2.0object-initializers

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


Solution

  • 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);