New C# 3.0 feature offers hope (at least for me)
My position on fields vs. Properties is pretty well known (See Item 1 in Effective C#). However, another group of developers that prefer fields, unless the getter or setter actually do real work. They feel that always using properties violates YAGNI (You ain't gonna need it). I suppose there is some truth in that. But my opinion has always been that the cost of binary compatibility is much greater than the cost of just making properties all the time.
Quite frankly, I think the YAGNI camp just believes it's more typing. Instead of this:
public int MyValue;
They need to type this:
private int myValue;
public int MyValue
{
get { return myValue; }
set { myValue = value; }
}
Starting with VS 2005, I think they are all wet anyway. I just type this:
public int myValue;
Then right click, select Refactor:Encapsulate field.
But even so, I'll admit that the 6 lines of code for such a simple feature is a bit heavy. The C# langauge team agreed. One of the C# team's greatest strength is that they recognize the most common idioms, and add convenient syntax to support them. In C# 3.0, I can write automatic properties. This syntax is very clean:
public int MyValue { get; set; }That produces the same IL as the six lines above. Automatic properties are gloriously sweet syntactic sugar around one of the most common idioms we use.
You can make read only automatic properties:
public string Name { get; }You can also make virtual automatic properties:
public virtual decimal Salary { get; set; }There's nothing magic about automatic properties. Just because the base class is implemented using automatic properties, the derived classes can override using automatic properties, or regular old property syntax.
So far though, other posts have only scratched the surface of the functionality provided by auto implemented properties. First, while I've only shown public properties, you can obviously create protected, internal, or protected internal properties.
What's more important is that you can also create properties with different accessors. Just like normal properties, you can limit the access to the setter:
public string Things { get; protected set; }You can also create a simple auto-implemented property that uses a private setter:
public string ReadThings { get; private set; }This gives you the possibility of creating a property using a very concise and clear syntax, and still limit any modifications to the backing field to your own class.
So, now who has any reason to argue for fields instead of properties?
See corrected update
Keith Farmer corrects a mistake