In the following setter, I can access the property backing field directly or through the getter. Is there a scenario when one would be preferred over the other?
public string Name {
get { return this.name; }
set {
if (value == this.name) return;
// or
// if (value == this.Name) return;
// ?
this.name = value;
NameChanged.Raise(this, this.name);
// or
// NameChanged.Raise(this, this.Name);
// ?
}
}
There is a related question. How would you initialize properties in the c-tor?
public MyClass(string name) { this.name = name; }
// or
public MyClass(string name) { Name = name; }
I use this.name, for the reason that at construction time the instance might be in an invalid/unstable/undefined state, so Name-setter validation might falsely fail. Any other opinions?
My personal opinion is to preferably use the property unless that results in the incorrect behaviour. What it comes down to is that using the property indicates a commitment to the semantics of your class and the design of your API.
Obviously sometimes there are going to be exceptions to this rule… sometimes the ‘property’ means something distinct to the value of the backing field (in your example, the property raises an event). If the internal use explicitly needs to avoid the semantics of the property (you don’t want the event to fire), then the backing field is the correct ‘second choice’.
On an unrelated note, for better or for worse, the Microsoft StyleCop application specifically prefers the convention of accessing private fields with the ‘this’ prefix to differentiate access of local variables and class fields (rather than prefixing such as ‘
_‘ or ‘m_‘ or variants thereof… which ironically are the convention used in legacy .NET framework code).