I love auto-implemented properties in C# but lately there's been this elephant standing in my cubicle and I don't know what to do with him.
If I use auto-implemented properties (hereafter "aip") then I no longer have a private backing field to use internally. This is fine because the aip has no side-effects. But what if later on I need to add some extra processing in the get or set?
Now I need to create a backing-field so I can expand my getters and setters. This is fine for external code using the class, because they won't notice the difference. But now all of the internal references to the aip are going to invoke these side-effects when they access the property. Now all internal access to the once aip must be refactored to use the backing-field.
So my question is, what do most of you do? Do you use auto-implemented properties or do you prefer to always use a backing-field? What do you think about properties with side-effects?
Eric Lippert has an excellent blog post that answers this question:
If the reason that motivated the
change from automatically implemented
property to explicitly implemented
property was to change the semantics
of the property then you should
evaluate whether the desired semantics
when accessing the property from
within the class are identical to or
different from the desired semantics
when accessing the property from
outside the class.
If the result of that investigation is
“from within the class, the desired
semantics of accessing this property
are different from the desired
semantics of accessing the property
from the outside”, then your edit has
introduced a bug. You should fix the
bug. If they are the same, then your
edit has not introduced a bug; keep
the implementation the same.
First of all, property getters should not have side-effects. This isn't always the case, but you should have a very good reason for it not being so.
That said, it's trivial to get a list of references to a property. If you change to an explicit property and want your private code to access your new backing variable, that should be a fairly easy modification to make.
I don't see any problem about using auto-implemented properties. imagine you have some property:
public string Name
{
get; set;
}
If you will need some additional processing in the future you just modify your property:
private string name;
public string Name
{
get { return this.name; }
set
{
if (!string.IsNullOrEmpty(value))
{
this.name = value;
}
}
}
In terms of separating commands from questions, having properties with side-effects is not really that nice. I'd prefer my objects to answer questions the same way as long as I haven't called any methods that clearly state that something is likely to change.
I always use AIP until I need a backing field. It's not very difficult to just swap:
public string MyString{get;set;}
for
private string myString;
public string MyString{get{return myString;} set{myString = value;}}
I think it's an unnecessary mess to always to the latter.