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.