tags:

views:

73

answers:

4

Hello,

Is there a way I can initialize the following runtime array to all trues without looping over it using a foreach?

Here is the declaration:

bool[] foo = new bool[someVariable.Count];

Thanks!

+2  A: 
bool[] bools = (new bool[someVariable.Count]).Select(x => !x).ToArray();

Sort of kidding. Kind of. Almost.

Deniz Dogan
You forgot the .Take(someVariable.Count)
Philippe
@Philippe: Not really, but I forgot that it needs to be `someVariable.Count` elements.
Deniz Dogan
That was kind of the joke you know :)
Philippe
Oh, should have understood that. :P
Deniz Dogan
Now that you changed the sample, it's not funny anymore, true :p But I have another idea: (new bool[Int32.MaxValue]).Select(x => !x).Take(someVariable.Count).ToArray(), that is perfect!
Philippe
+4  A: 
bool[] foo = Enumerable.Repeat(true, someVariable.Count)
                       .ToArray();
Ani
+1  A: 

Is any kind of explicit looping forbidden, or are you only concerned about avoiding foreach?

bool[] foo = new bool[someVariable.Count];
for (int i = 0; i < foo.Length; i++) foo[i] = true;
LukeH
I'm not against it nor is it forbidden, I was just wondering if there was a better way or a built in language construct :)
Polaris878
A: 
bool[] foo = new bool[]{true,true,true,...};

This is the only way in C# known to me to initialize an Array to a certain value other than the default value which does not involve creating other temporary objects. It would be great if class Array had some method like Fill() or Set().

Correcty me if Iam wrong.

codymanix
Array initialisers still need to overwrite the "default" array with new data, and that new data has to be stored somewhere prior to being copied into the array. For simple types the data is baked into the assembly metadata at compile-time and then copied directly into the array at run-time. For non-simple types the initialiser is translated into IL to explicitly create and add the elements individually at run-time. (As far as I'm aware these are just implementation details rather than documented guarantees.) http://bartdesmet.net/blogs/bart/archive/2008/08/21/how-c-array-initializers-work.aspx
LukeH