What is the benefit of using get and set properties in the following example?:
class Program
{
public class MyClass
{
private int age;
public int persons_age
{
get
{
return age;
}
set
{
age = value;
}
}
}
static void Main(string[] args)
{
MyClass homer = new MyClass();
homer.persons_age = 45; //uses the set property
homer.persons_age = 56; //overwrites the value set by the line above to 56
int homersage=homer.persons_age; //uses the get property
Console.WriteLine(homersage);
}
}
what is the difference between doing that and the following?:
public class MyClass
{
public int age;
}
static void Main(string[] args)
{
MyClass homer = new MyClass();
homer.age = 45;
homer.age = 56; //overwrites the value set by the line above to 56
int homersage=homer.age;
Console.WriteLine(homersage);
}
What is the benefit of using the get and set property when there is no difference at all in what the above two programs do? Unlike the scenario where the client has limited ability to assign vales to the field via the set method through some logic checking, in this situation I don't see any functional difference between the two programs show here.
Also, some programming books use the phrase "...breaks the client code" if such properties are not used for class fields. Can someone explain this?
Thanks.