I wrote my first class with automatic properties in Orcas today...
... then I found myself staring at the screen.
It's an interface!
No,it's a class!
Wait, it is a class!
I'd say the syntax is still growing on me.
I'm sure some people will say – why use properties at all? If you don't need special code in the get and set methods – why not just use a public field?
The quick answer is: reflection. There are many forms of magic that will only occur if you expose state using public properties.
Comments
I wrote a dll for an Orcas project that, a couple weeks later, I wanted to reuse, but couldn't 'cuz of the few lambdas, default properties and collection initializers.
Overall progress is great, it's just the year or two that we transition that sucks.
public string Name { get; private set; }
Now I can assign the Name in the constructor, and external code can't mutate it. THAT beats a public field hands down, for just a teensy bit more typing.
Note that if you use the latter in a class library and later decide you wanted properties, you'd potentially break existing clients (with automatic properties, you just change it to normal properties and add any implementation you fancy). Also properties work in databinding scenarios that fields don't :)
As Daniel pointed out, there are some scenarios where public properties are a must. If you want to use your class with data binding, or with some of the serializers (XmlSerializer), than they use reflection to find public properties only.
Could it be that the behaviour changed between .NET 1.1 and .NET 2.0?
I do recall some issues with databinding and the need to create properties, but I'm currently reworking a webservice in .NET 2.0 that was originally written in .NET 1.1 and I'm adding new classes that are being serialized (by hand and by the .NET framework itself for SOAP stuff) without properties but with public fields and I've yet to run into a problem.
I created a very small test app just now. Two classes with a string, an int, a float and a DateTime. One class made the fields public and one used properties. The XML that came out the serializer is identical.
Or is my test too simple?
Just curious.
Data binding (at least in ASP.NET) still looks at public properties only...
I would still like something like:
public property int Id;
private property int Id;
public readonly property int Id;
And, for regular properties, it would be cool to:
public int Id
{
int id = 1; // field inside of property block, nice when we lazy load.
get { return id; }
}