XmlSchemaClassGenerator
XmlSchemaClassGenerator copied to clipboard
Auto-Implemented Properties not used
Hello, I'm not sure to understand when but sometimes auto-implemented properties are not used. For example:
<?xml version="1.0"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="root">
<xs:complexType>
<xs:sequence>
<xs:element maxOccurs="unbounded" name="elem" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
generates
public partial class Root
{
private System.Collections.ObjectModel.Collection<object> _elem;
public System.Collections.ObjectModel.Collection<object> Elem
{
get { return this._elem; }
private set { this._elem = value; }
}
which could be simplied with
public System.Collections.ObjectModel.Collection<object> Elem { get; private set; }
Is this expected ?
Backing fields are generated whenever initialization needs to occur or additional processing is done in the setter (databinding). The relevant line is this: https://github.com/mganss/XmlSchemaClassGenerator/blob/dee1ac0e22c80d65bb6e7c3224606b93f622cae8/XmlSchemaClassGenerator/TypeModel.cs#L756
Since C# 6 there are auto-property initializers which could be used for some of these cases but IMO that would just be 💄
Thanks for mentioning the specific line.
I'm looking for a clean generated class. Initialization can be done on the property like this
public int I { get; set; } = 5
And why do array and collection need a backing field ?
Collections are always initialized with a new object of the chosen collection type. I can't remember exactly why we're always using a backing field instead of calling the setter from the constructor, but it would probably have been more complicated once databinding comes into play. That, or something to do with CodeDom.
If you want to tackle this and use C# 6 syntax for initialization instead, go for it. PRs always welcome 😄 Keep in mind, though, that when databinding is enabled we'll always need a setter body and a backing field.
I would like to see this enhancement implemented if it won't break anything. Particulary adding awarenes of initialisation to the default value (even if it's specified) and using C#6 initialiser for properties rather than backing fields.