I want to get the default value set on an auto property to do some IL weaving with Fody.
As I understand, the initialization is just a syntactic sugar that sets the backing field in the constructor. So I thought the default value is created with the instructions from the end of the last property's initialization to the stfld
instruction that sets the backing field of the current property.
However this assumes the initialization is always done as the first thing in the constructor. Is that a correct assumption? Is there any edge cases to consider such as optimizations?
I found this pdf file titled Upcoming Features in C# which describes the new language features for C# 6.
Here is the section about auto property initializers (Emphasis is mine):
The initializer directly initializes the backing field; it doesn’t work through the setter of the autoproperty.
The initializers are executed in order as written, just as – and along with – field initializers.
Just like field initializers, auto-property initializers cannot reference ‘this’ – after all they are executed before the object is properly initialized. This would mean that there aren’t a whole lot of interesting choices for what to initialize the auto-properties to. However, primary constructors change that. Autoproperty initializers and primary constructors thus enhance each other.
Since the field initializers and the auto property initializers are treated equally, the following section from C# specification should apply to the auto property initialization as well.
10.11.3 Constructor execution
Variable initializers are transformed into assignment statements, and these assignment statements are executed before the invocation of the base class instance constructor. This ordering ensures that all instance fields are initialized by their variable initializers before any statements that have access to that instance are executed.
...
It is useful to think of instance variable initializers and constructor initializers as statements that are automatically inserted before the constructor-body.