Is a good practice to initialize private data members from within ctor by calling the associated properties instead of the data members themselves?
interface IAnimal
{
string Name { get; set; }
}
class Dog : IAnimal
{
private string name;
public Dog(string name)
{
Name = name;
}
public string Name
{
get { return name; }
set {开发者_如何转开发 name = value; }
}
}
In general, it's better to go through the property getter and setter whenever possible unless there is a specific reason not to. If the property setter has a side effect (like firing a notification) that you don't want in a specific situation, it's ok to assign to the backing field directly from within the object, but try to avoid getting into that sort of situation.
The reason it's good to use the property getter and setter, even in the implementing class itself: when/if you need to change the implementation of the getter/setter in the future, such as adding needed side effects, your code will already be in a good position to honor the new getter/setter semantics.
精彩评论