Initializing child objects in constructor

Jan 22, 2009 at 4:34 PM
I've run into a problem with the generated code for a schema. Here is a sample schema that will demonstrate my issue:

<?xml version="1.0" encoding="utf-8" ?>
<xs:schema elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="MyObject">
    <xs:complexType>
      <xs:all>
        <xs:element minOccurs="0" maxOccurs="1" name="Option1">
          <xs:complexType>
            <xs:simpleContent>
              <xs:extension base="xs:string">
                <xs:attribute name="Opt1Attr1" type="xs:string" use="required" />
                <xs:attribute name="Opt1Attr2" type="xs:int" use="required" />
              </xs:extension>
            </xs:simpleContent>
          </xs:complexType>
        </xs:element>
        <xs:element name="Option2">
          <xs:complexType>
            <xs:simpleContent>
              <xs:extension base="xs:string">
                <xs:attribute name="Opt2Attr1" type="xs:date" use="required" />
              </xs:extension>
            </xs:simpleContent>
          </xs:complexType>
        </xs:element>
      </xs:all>
    </xs:complexType>
  </xs:element>
</xs:schema>

After generating code I can now create xml using C#.

Scenario:
I create MyObject. Since Option1 and Option2 are optional child elements I have to explicitly set them to null if I don't want them to appear in my xml.
My XML looks like this after I serialize and set my child objects to null:

  <?xml version="1.0" ?>
  <MyObject xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />

However, when I deserialize this back into a MyObject object, the object has a value for Option1 and Option2 again. Opt1Attr2 on Option1 is set to 0 (as default for integer), but I have no way to determine if this was set in the xml or if it was generated by the deserialize method. Wouldn't it work better if I have to explicitly creat Option1 and Option2 on MyObject if they are optional child elements, and wouldn't it also be better not to automatically create these in the constructor if they don't exist in the xml?

Thanks.
Jan 22, 2009 at 5:38 PM
This discussion has been copied to a work item. Click here to go to the work item and continue the discussion.