While answering a question on SO yesterday, I noticed that if an object is initialized using an Object Initializer, the compiler creates an extra local variable.
Con
Thread-safety and atomicity.
First, consider this line of code:
MyObject foo = new MyObject { Name = "foo", Value = 42 };
Anybody reading that statement might reasonably assume that the construction of the foo
object will be atomic. Before the assignment the object doesn't exist at all. Once the assignment has completed the object exists and is in the expected state.
Now consider two possible ways of translating that code:
// #1
MyObject foo = new MyObject();
foo.Name = "foo";
foo.Value = 42;
// #2
MyObject temp = new MyObject(); // temp will be a compiler-generated name
temp.Name = "foo";
temp.Value = 42;
MyObject foo = temp;
In the first case the foo
object is instantiated on the first line, but it won't be in the expected state until the final line has finished executing. What happens if another thread tries to access the object before the last line has executed? The object will be in a semi-initialised state.
In the second case the foo
object doesn't exist until the final line when it is assigned from temp
. Since reference assignment is an atomic operation this gives exactly the same semantics as the original, single-line assignment statement. ie, The foo
object never exists in a semi-initialised state.