C# OOPChapter 3 · C# Object Oriented Programming
Encapsulating with properties
Properties combine a private field with accessors called get and set. This protects class data by controlling how values are read or written.
Worked example
class SkyItem {
private int _density;
public int Density {
get { return _density; }
set {
if (value >= 0) _density = value;
}
}
}How it reads
- private int _density hides the internal value
- get { return _density; } runs when reading the property
- set { ... } runs when writing, with value representing incoming data

Cloud tip: Use auto-implemented properties like public string Name { get; set; } when no validation logic is needed.


