Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

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

like image 260
Farhan Hafeez Avatar asked Jan 08 '13 07:01

Farhan Hafeez


People also ask

Can you initialize an array with a variable in C?

The C99 standard allows variable sized arrays (see this). But, unlike the normal arrays, variable sized arrays cannot be initialized.

How do we initialize an array in C?

The initializer for an array is a comma-separated list of constant expressions enclosed in braces ( { } ). The initializer is preceded by an equal sign ( = ). You do not need to initialize all elements in an array.

How do you declare an integer in an array?

There are various ways in which you can declare an array in Java: float floatArray[]; // Initialize later int[] integerArray = new int[10]; String[] array = new String[] {"a", "b"};


2 Answers

int[] myIntArray = Enumerable.Repeat(-1, 20).ToArray();
like image 62
scartag Avatar answered Oct 12 '22 04:10

scartag


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.

like image 35
SWeko Avatar answered Oct 12 '22 05:10

SWeko