Properties instead of public fields
A property looks like a value from outside and like a method inside. It is the polite way to expose data from a class.
A property in C#
C#
public class Lesson
{
private int minutes;
public int Minutes
{
get { return minutes; }
set
{
if (value >= 0)
{
minutes = value;
}
}
}
}Why not just a public field
- A property can reject a bad value, as the setter above rejects a negative number.
- A property can be read only or write only when that is the right rule.
- The storage can change later without breaking every caller.
Naming habit. A property uses a capital first letter and its backing field uses a lower case one. The pattern makes it obvious which is which at a glance.
When objects are no longer needed, the runtime reclaims them. That process is garbage collection.