Direct array initialization with a constant value

前端 未结 6 1527
心在旅途
心在旅途 2020-12-09 14:44

Whenever you allocate a new array in C# with

new T[length]

the array entries are set to the default of T. That is null for th

6条回答
  •  不思量自难忘°
    2020-12-09 15:18

    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".

提交回复
热议问题