TL ; DR:
An access modifier controls who can see a member of a class. The two you'll use most are
public(anyone) andprivate(only this class).Make data
privateso callers can't break invariants by writing to it. Expose what they need throughpublicmethods:class Dog { private string name; // hidden from outside public Dog(string name) { // anyone can construct this.name = name; } public string GetName() { // controlled read access return name; } }
Outside the class,
rex.nameis a compile error. Userex.GetName()instead.
Full lesson:
So far every field we wrote was public — anyone could read or write it. That's convenient, but it leaks the class's internals. If you later decide to validate the data or compute it differently, every caller in the codebase breaks.
Encapsulation
Encapsulation is the idea that an object's data should be hidden behind methods. The class controls how it's read and written; outside code only sees the API.
class Account {
private decimal balance;
public void Deposit(decimal amount) {
if (amount < 0) throw new ArgumentException();
balance += amount;
}
}
If balance were public, anyone could write account.balance = -1000; and break the invariant.
The two main modifiers
public | Visible everywhere. |
private | Visible only inside the same class. |
(There are also protected and internal, which we'll cover when we get to inheritance and assemblies.)
Your task
The Dog class's name field is now private. Add a public string GetName() method that returns it, so the harness in Solution.MainFunction can read the dog's name.
Dog's name: RexFree plan: 30 tutor messages. PRO is unlimited.
