tags:

views:

60

answers:

1
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; }
    }
}
+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
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
Consider that many guys use auto properties, then it is OK to do initialization that way.
Lex Li