Direct array initialization with a constant value Direct array initialization with a constant value arrays arrays

Direct array initialization with a constant value


Similar to Dan's answer but without the need of using collections:

int[] myArray = Enumerable.Repeat(-1, 100).ToArray();


It's not redundant.

Suppose an exception is thrown during your initialization loop. If the CLR hasn't cleared the memory first, you might be able to "see" the original uninitialized memory, which is a very bad idea, particularly from a security standpoint. That's why the CLR guarantees that any newly allocated memory is wiped to a 0 bit pattern.

The same argument holds for fields in an object, by the way.

I suppose in both cases the CLR could check that you're not going to make the array visible elsewhere before finishing initialization, but it's a complicated check to avoid a pretty simple "wipe this area of memory".


If you buy into Arrays considered somewhat harmful, then your question would be moot as you would write:

var myArray = new List<int>(Enumerable.Repeat(-1, 100));