Wednesday, November 07, 2007

Auto Properties & Object/Collection initializers - the presenter's friend

From being here at TechEd2007, I have noticed one thing, if nothing else (actually I have noticed lots else) is that the presenters bashing out code in live demos love auto properties and the quick initialisation capabilities in C#3.0. It makes the job of getting straight down to the umpteenth

from a in b
where c
select d

so much easier. A bit like using dynamic SQL, it saves time/errors when cutting code in front of a live audience, and so it has cropped up in loads of sessions.

Coming from a coding environment where we produce web, win and ajax controls, however, I can't say that auto properties will be figuring much in my production code; for the one reason that they cannot be decorated with attributes. Attributes are essential when surfacing control properties for governing designtime stuff like visibility, serialisation and categorisation as well as runtime stuff like data binding. Even simple private member variables need stuff like this when they are encapsulated as public properties.

The initializers on the other hand are an excellent labour-saving piece of <motsDuJour>Syntactical Sugar</motsDuJour>. Given that all that happens when the syntax is compiled is that the longer-winded versions of the constructs are created in IL, they can be seen as akin to the using block's expansion to a try-finally dispose construct in the corresponding IL.

Good stuff.

1 comment:

Simon said...

Interesting, I also thought that you couldn't use attributes on properties for some reason. However, I was wrong:

public class Data
public int SomeNumber { get; set; }

class Program
static void Main(string[] args)
using (XmlWriter w = XmlWriter.Create(@"c:\temp\test.xml"))
XmlSerializer s = new XmlSerializer(typeof (Data));
s.Serialize(w, new Data { SomeNumber = 5 });