Reputation: 41473
Is there a way I can initialize the following runtime array to all true
s without looping over it using a foreach?
Here is the declaration:
bool[] foo = new bool[someVariable.Count];
Thanks!
Upvotes: 2
Views: 728
Reputation: 29468
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.
Upvotes: 0
Reputation: 269298
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;
Upvotes: 1
Reputation: 113402
bool[] foo = Enumerable.Repeat(true, someVariable.Count)
.ToArray();
Upvotes: 6
Reputation: 26217
bool[] bools = (new bool[someVariable.Count]).Select(x => !x).ToArray();
Sort of kidding. Kind of. Almost.
Upvotes: 2