EDIT: Although the original answer below is still accurate, it looks like it's a mixture of debugging and optimization information that matters here.
From my experiments:
Compiler flags Result /o+ /debug- Finalizer runs /o+ /debug+ Finalizer runs /o- /debug- Finalizer runs /o- /debug+ Finalizer does *not* run
The finalizer is still being called in my field when compiling on the command line using /o+ . I assume that you are working in a debugger that changes the behavior of the GC. Without a debugger, GC collects everything it can prove that it will never be read. With the debugger, I believe that the GC will not collect any objects that still have stack references, even if there is no code to read the variables in question.
Now, with the object initializer, the compiler code includes an additional link on the stack. This line:
Zombie z = new Zombie { Name = "Guy" };
effective:
Zombie tmp = new Zombe(); tmp.Name = "Guy"; Zombie z = tmp;
Assignment z is performed only after all properties have been set.
I assume that the tmp variable here supports saving the object.
Jon Skeet Mar 17 '12 at 20:10 2012-03-17 20:10
source share