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 {}?

Community
  • 1
  • 1
Farhan Hafeez
  • 634
  • 1
  • 6
  • 22
  • 4
    Also check out this http://stackoverflow.com/questions/13980570/how-to-intialize-integer-array-in-c-sharp/ which discusses how to do it efficiently and http://stackoverflow.com/questions/10519275/high-memory-consumption-with-enumerable-range how not to use ToArray for large arrays. – Alexei Levenkov Jan 08 '13 at 07:55

3 Answers3

45
int[] myIntArray = Enumerable.Repeat(-1, 20).ToArray();
Eren Ersönmez
  • 38,383
  • 7
  • 71
  • 92
scartag
  • 17,548
  • 3
  • 48
  • 52
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.

SWeko
  • 30,434
  • 10
  • 71
  • 106
14

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();
Habib
  • 219,104
  • 29
  • 407
  • 436
mlorbetske
  • 5,529
  • 2
  • 28
  • 40