In cases where we are using properties with backing fields, is it good practice - in terms of OOP and encapsulation - to access these backing fields directly or should we always go through the class property?
public class SomeClass
{
private string _name;
public string Name
{
get { return _name; }
set { _name = value == null ? "" : value; }
}
public void SetField()
{
...
_name = "alice";
...
}
public void SetProperty()
{
...
Name = "bob";
...
}
}
My instinct is to always use the property and never use the field except in the getter/setter but I don't know if this is an personal preference or there is a preferred standard or rule.
Just to clarify because I don't want to be misunderstood, I know that setting _name
and Name
are different things and I'm not asking if a setter like the one in my example is a good idea.
EDIT: Im not asking if and when I should use auto properties like the duplicated question/answer mentions.