I saw NRE when using array initializer in object initializer and there was a update and https://github.com/dotnet/roslyn/wiki/New-Language-Features-in-C%23-6#extension-add-methods-in-collection-initializers but still I cannot understand.
var arr = new int[] { 1, 2, 3 }
generate IL code using stelem
.
But int[] arr = { 1, 2, 3 }
generate IL code using RuntimeHelpers.InitializeArray
. I think it is using Array.Add
extension method which was talk in that answer.
But in object initializer, all array initializer generate second code. An example,
new A() {
arr = new int[] { 1, 2, 3 }
}
Array arr
is created using RuntimeHelpers.InitializingArray
too. Then, doesn't it mean there isn't any problem in next code?
new A() {
arr = { 1, 2, 3 } // Compiler error!
}
Not like old version of c# compiler, it makes compiler error saying system.array does not contain a definition for Add
. What's happening?
EDIT
I thought just syntax without new []
makes differences but actually more than three elements makes different IL code.