How about a bool property to control whether the Property.Get creates an instance if field is null?

May 5, 2009 at 5:01 PM
Edited May 5, 2009 at 5:02 PM
I long considered that it might make more sense to have proeprties that look like:


  private ComplexThing _something;

  public ComplexThing Something{
    get{
      if(_autoInitNullFields && _something == null)
        _something = new ComplexThing();
      return _something;
  }
 }

This way, I dont have to init everything before I use it, and I dont create an entire tree of objects from one "new" statement, if I'm not going to use them.

Doesnt the XmlSerializer put a tag if the instance is not null? That means that precreating all objects would result in XML with empty tags?


Suppose my code above also had a ComplexThing2, and I never set any property on it..

If the owner of ComplexThing and ComplexThing2 were serialized, and your "precreate everything" constructor were used, it would look like:

<root>
  <complexThing>
    <elementA>I set this</elementA>
  </complexThing>
  <complexThing2>
    <elementB></elementB>
  </complexThing2>
</root>

??


When it could just be:

<root>
  <complexThing>
    <elementA>I set this</elementA>
  </complexThing>
</root>


If init were done upon access rather than creation?

Note: the boolean _autoInitNullFields exists to be turned to false before serializing, so the serializer pulling every property out during serialize doesnt cause an init of the field..

Aug 2, 2009 at 2:05 AM

It would be nice huh.  Something .NET itself should have done WAY better at.  I've spent lots of time in the code, and I dunno how easy it would be to implement this, but it would be great. 

See also issue #8118

Sep 10, 2009 at 3:21 PM

The problem here lies with the Xsd2Code.  Once the code has been generated using the build in MS funcionality, the xsd2code enhances the generated code, and generates a contrstructor.  In that constructor it checks for things being null, and creates instances.  This isssue has been raised a fair few times.  I think that the code should not auto generate a constructor, unless you opt in.  Second, it should not auto instatiate properties, especially as it does this for nullable fields.