20

Possible Duplicate:
How do I quicky fill an array with a specific value?

Is there a way to initialize an integer array with a single value like -1 without having to explicitly assign each item?

Basically, if I have

int[] MyIntArray = new int[SomeCount];

All items are assigned 0 by default. Is there a way to change that value to -1 without using a loop? or assigning explicitly each item using {}?

1

3 Answers 3

45
int[] myIntArray = Enumerable.Repeat(-1, 20).ToArray();
Sign up to request clarification or add additional context in comments.

4 Comments

Don't forget the .ToArray()
+1 for all ToArray once. Before using please read High memory consumption with Enumerable.Range if your array is large.
And for types other than int, use the template form, eg. Enumerable.Repeat<UInt32>(1,20).ToArray();
@dlchambers or Enumerable.Repeat(1U, 20).ToArray();
18

You could use the Enumerable.Repeat method

int[] myIntArray = Enumerable.Repeat(1234, 1000).ToArray()

will create an array of 1000 elements, that all have the value of 1234.

1 Comment

Only answer that is clear.
15

If you've got a single value (or just a few) you can set them explicitly using a collection initializer

int[] MyIntArray = new int[] { -1 };

If you've got lots, you can use Enumerable.Repeat like this

int[] MyIntArray = Enumerable.Repeat(-1, YourArraySize).ToArray();

3 Comments

put some size in new int[Size] and this statement will not work. Even if you put a static size like 50. So, I don't think that this is right answer.
@FarhanHafeez You're absolutely correct, I originally misread the question and immediately went to edit my answer, my apologies
Only answer to address the "without using a loop"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.