Learn C# · lesson 40 of 61 · about 9 minutes
Encapsulation
Guard the hero's purse: protect an object's data so it can only change in valid ways.
What you'll learn
- Keep fields private
- Validate in methods and property setters
- Throw an exception for invalid values
The hero's purse
At the market, the hero wants an elixir for 25 gold and then a cape for 40. The gold goes into a Purse that guards it: the number lives in a private field _gold, the read-only property Gold lets anyone see it, and Spend() is the only way to take some. Spend() refuses amounts that aren't above 0 or are more than there is, and says whether it worked, so the market can say what the hero could and couldn't buy.
Guarding the data
Encapsulation means an object looks after its own data. Outside code asks the object to do things; the object checks the request.
- Keep fields
private(C# names them_like_thisby convention) - Expose read-only properties
- Check values in methods or in a property's
set, wherevalueis the new value - Reject bad requests with
throw new ArgumentException("message")
A counter only its methods can change
var c = new Clicker();
c.Click();
c.Click();
Console.WriteLine(c.Count);
class Clicker
{
private int _count;
public int Count => _count;
public void Click() => _count++;
}Output
2Checking in a setter
A property's set can check value before storing it, and throw an exception to refuse it. The field keeps its old value.
A thermostat
var t = new Thermostat();
t.Target = 21;
Console.WriteLine(t.Target);
try
{
t.Target = 60;
}
catch (ArgumentException e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine(t.Target);
class Thermostat
{
private int _target = 18;
public int Target
{
get => _target;
set
{
if (value < 5 || value > 30) throw new ArgumentException($"{value} is out of range");
_target = value;
}
}
}Output
21
60 is out of range
21Tip
try and catch let a program recover from an exception. You'll learn more about them in the next unit.
Now try it yourself
This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.