Initializing a Direct Array with a Constant Value

Whenever you allocate a new array in C # using

new T[length] 

array entries have a default value for T. This is null for the case when T is a reference type or the result of the default constructor T , if T is the value type.

In my case, I want to initialize an Int32 array with a value of -1:

 var myArray = new int[100]; for (int i=0; i<myArray.Length; i++) { myArray[i] = -1; } 

So, after the memory is reserved for the array, the CLR iterates over the new allocated memory and sets all the entries to default (int) = 0. After that, my code sets all the entries to -1.

This makes initialization redundant. Does JIT describe this and neglect initialization to 0, and if not, is there a way to directly initialize a piece of memory with a user-defined value?

Referring to initializing a C # array with a value other than the default , using Enumerable.Repeat(value, length).ToArray() not an option because Enumerable.ToArray allocates a new array and copies the values ​​to it afterwards.

+42
arrays initialization c # constants
Mar 15 '09 at 23:37
source share
4 answers

This is not redundant.

Assume that an exception occurs during the initialization cycle. If the CLR does not clear the memory first, you can "see" the original uninitialized memory, which is a very bad idea, especially from a security point of view. Therefore, the CLR ensures that any newly allocated memory is erased to a 0-bit pattern.

The same argument holds for fields in the object.

I believe that in both cases, the CLR can verify that you are not going to make the array visible elsewhere until the initialization is complete, but this is a difficult test to avoid the rather simple β€œwipe this memory area”.

+31
Mar 15 '09 at 23:42
source share

Like Dan, but without the need for collections:

 int[] myArray = Enumerable.Repeat(-1, 100).ToArray(); 
+25
Sep 29 '09 at 17:33
source share

If you buy into arrays that are considered somewhat harmful , then your question will be debatable, as you would write:

 var myArray = new List<int>(Enumerable.Repeat(-1, 100)); 
+10
16 Mar '09 at 0:08
source share

I very much doubt that JIT optimizes the default setting for this scenario. The reason is that this will be the observed difference. Consider the following slightly modified scenario.

 obj.myArray = new int[100]; for (int i=0; i<myArray.Length; i++) { obj.myArray[i] = -1; } 

This is entirely possible for the cycle. At least for JIT, it is probably impossible to prove that this is not so. If this was done, and the CLR did not initialize the default memory, the result would be observable if you still had a link to obj.

+3
Mar 15 '09 at 23:44
source share



All Articles