Encapsulation C# newbie
c#, encapsulation, get, set
Solution
Indeed, creating an auto-property as follows:
public string Name { get; set; }
is identical to building a property backed by a field:
private string _name;
public string Name {
get { return _name; }
set { _name = value; }
}
The point of these properties is not to hide data. As you observed, they don't do this. Instead, these properties can do other stuff instead of just working with a field:
public string Name {
get { return _name; }
set { if (value == null) throw new Exception("GTFO!"); _name = value; }
}
Another thing is, you can make properties virtual:
public virtual string Name { get; set; }
which, if overridden, can provide different results and behaviours in a derived class.
Problem
New to C#, and I understand that encapsulation is just a way of "protecting data". But I am still unclear. I thought that the point of get and set accessors were to add tests within those methods to check to see if parameters meet certain criteria, before allowing an external function to get and set anything, like this: ``` private string myName; public string MyName;// this is a property, speical to c#, which sets the backing field. private string myName = "mary";// the backing field. public string MyName // this is a property, which sets/gets the backing field. { get { return myName; } set { if (value != "Silly Woman"){ myName = value; } } } ``` But I've been seeing code in c# which just looks like this: ``` public string MyName { get; set; } ``` Why would you just have a get and set with nothing in there, - isn't that the same as just declaring your private backing field public? If you can just get and set it from outside, why wouldn't you just do it directly?