I am teaching myself C# and I was curious about the need for declaring private member variables that are accessed by public properties. The textbook I'm using says this is for the sake of encapsulation, but why do I need the private variables to begin with if the properties can be changed depending on their 'get' or 'set' functions? Here's an example:
namespace Practice
{
struct Person
{
private int id;
private string name;
public int ID { get {return id;} set {id = value;} }
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main(string[] args)
{
Person person = new Person();
person.ID = 548;
person.Name = "Dude";
Console.WriteLine(person.Name);
}
}
}
So Name and ID operate the exact same way, so what's the purpose of declaring private int id
and private string name
?