Initialize an integer array with a single value in C# .NET [duplicate]

Posted on

Problem :

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

Solution :

int[] myIntArray = Enumerable.Repeat(-1, 20).ToArray();

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.

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();

Leave a Reply

Your email address will not be published. Required fields are marked *