Automatic properties and initilaization

Mar 1, 2010 at 2:10 PM


I have noticed that also if you set automatic properties to true the xsd elements are generated with a field behind only to initialize them in the constructor.

But you don't need it, you can initialize the property directly in the constructor:

public MyParentElement()
  this.MyChildElement = new MyChildElement();

public MyChildElement MyChildElement {get; set;}

For the lazy loading (you call it "laSyloading" is that a type error?) is better to use the coalescent operator "??", which should be a little bit more performant:

public MyChildElement
  get { return this.myChildElement ?? (this.myChildElement = new MyChildElement()); }
  set { this.myChildElement = value; }

Last but not least a good suggestion to improve your tool for the advanced users, in the last period we worked a lot with T4 templates (here an article about them, we used them to generate business objects from service references. At the end we have added to the template generator an option to specify the get and set template for the properties as a format string:

GetTemplate="return this.{0} ?? (this.{0} = new {1}());";
SetTemplate="this.{0} = value;";

Where {0} is replaced with the field name, {1} with the field / property type and {2} with the property name. We use two different get/set templates, one for the attributes and one for the navigation properties (xsd elements). If you are asking yourself why we have also a place holder for the property name, is because we use lambda expressions to raise the property changed event (, so our get and set look a little different:

GetTemplate="return this.{0} ?? (this.{2} = new {1}());";
SetTemplate="this.SetPropertyValue<{1}>(ref this.{0}, value, () => this.{2});";
Together with the base class name this technique gives a lot of flexibility and it isn't at all complicated to implement.

Mar 8, 2010 at 9:16 PM

About T4, don't forget that Xsd2Code also generates VB code.

At this time, i don't know T4, i need to learn it.