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; }
}
}
views:
60answers:
1
+7
A:
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.
dthorpe
2010-04-14 01:57:52
Because the object instance has not been completely constructed when the ctor is in progress, I am sure the event (if any) is always null. It means notifications never fires because the if construct always returns false.OK. I will use this mechanism consistently from now on.Thank you for your comment.
yuko.aihara
2010-04-14 02:21:43
Consider that many guys use auto properties, then it is OK to do initialization that way.
Lex Li
2010-04-14 06:47:33