If I have this object, which has a child object as an automatic property:
public class ParentObject
{
public ChildObject Child { get; set; } = new ChildObject();
}
At what point is the Child
initialised? During construction of the ParentObject
, or just as the first 'get' of ChildObject
occurs?
I ask because I'm considering reworking some old Net 2 code. The old code has explicit backing fields like:
public class ParentObject
{
private ChildObject child;
public ChildObject Child
{
get { return this.child; }
set { this.child = value; }
}
}
..which means that Child
is null until explicitly set. It would be nice to use the new style of auto-property with default initialiser (which brings further benefits in that we don't need to make checks such as:
if (parentobject.Child == null) parentobject.Child = new Child();
But if the child property is initialised on construction of the parent, then it's 'bad' (not optimal) for the cases where we serialize and send the parent object (potentially with an empty child field) over the wire.
The property — specifically, the underlying backing field that's created by the compiler — is initialized when the ParentObject
is instantiated (just before the constructor is executed). This works similarly to normal fields with initializers (e.g. private ChildObject child = new ChildObject();
).
Therefore, as you have correctly noted, that is not the right way to refactor your existing code. You should simply leave out the initializer:
public class ParentObject
{
public ChildObject Child { get; set; }
}
... resulting the original auto-property syntax introduced way back in C# 3.0 that we have come to know and love (before the new stuff like property initializers came in).