Nov 4, 2009 at 3:29 PM
Edited Nov 4, 2009 at 3:35 PM
Don't forget, that with lazy instantiation, when serializing the XmlSerializer is accessing the properties so XmlSeralizer will cause everything to instantiate...
i.e. right now, lazy instantiation is of no benefit for time/processing saving when serializing, because XmlSerializer is going to access everything that is not [XmlIgnore] and instantiate all the properties anyway..
Suggest you make a class-wide boolean variable/property _serializing = false; and set it to true when Serialize() is called.. Then your lazy code can look like:
if(!_serializing && theField == null)
theField = new TheField();
As to how this causes bugs, the serialized XML differs from before. Suppose we have a dumb service that relies on the presence/absence of an element TheField. Suppose we have a class:
property A: int
property TheField: TheFieldClass
With NOT LAZY instantiation, if TheField is null we get:
Now with lazy, we get:
Now suppose TheFieldClass has an int property B:
Even though I as a programmer never touched the property, just serializing it caused it to exist in the xml and now have values in primitive fields which might cause services that rely on present/absent tags, to fail..