DigitalZebra
DigitalZebra

Reputation: 41473

Initialize runtime value-type array with specific value?

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!

Upvotes: 2

Views: 728

Answers (4)

codymanix
codymanix

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

LukeH
LukeH

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

Ani
Ani

Reputation: 113402

bool[] foo = Enumerable.Repeat(true, someVariable.Count)
                       .ToArray();

Upvotes: 6

Deniz Dogan
Deniz Dogan

Reputation: 26217

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

Sort of kidding. Kind of. Almost.

Upvotes: 2

Related Questions