Direct array initialization with a constant value

前端 未结 6 1557
心在旅途
心在旅途 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:15

    I highly doubt that the JIT will optimize away the default set for this scenario. The reason being is that this would be an observable difference. Consider the following slightly altered scenario.

    obj.myArray = new int[100];
    for (int i=0; i

    It's entirely possible for the loop to throw. At least, it's probably not possible for the JIT to prove it doesn't. If it did throw and the CLR did not default initialize the memory, the result would be observable if you still had a reference to obj.

提交回复
热议问题