2

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
  • 1
    Any reason why you are not using foreach. That looks like the most straightforward way of doing this. Commented Oct 7, 2010 at 16:25
  • Yes you are correct, it is. I was just wondering if there was another way or some sort of language construct that might do this for you/hide this. Commented Oct 7, 2010 at 18:46

4 Answers 4

6
bool[] foo = Enumerable.Repeat(true, someVariable.Count)
                       .ToArray();
Sign up to request clarification or add additional context in comments.

Comments

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

Sort of kidding. Kind of. Almost.

5 Comments

You forgot the .Take(someVariable.Count)
@Philippe: Not really, but I forgot that it needs to be someVariable.Count elements.
That was kind of the joke you know :)
Oh, should have understood that. :P
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!
1

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;

1 Comment

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

1 Comment

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.) bartdesmet.net/blogs/bart/archive/2008/08/21/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.