c# · level 2 · unit 2 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Properties let the class decide who can change what.
A public field lets any code put anything in it, even a balance of -20. A looks like a field from outside, but it has two accessors: get runs when code reads it, and set runs when code changes it. { get; set; } makes a plain one.
Mark an and only code inside the class may use it. { get; private set; } lets anyone read Balance, but only the account itself can change it, through a method like Deposit that checks every amount first.
Outside code that tries acc.Balance = 1000; is refused with CS0272. From now on, classes keep their data in properties.
using System;
var acc = new Account("Sam");
acc.Deposit(50);
acc.Deposit(-20);
Console.WriteLine($"{acc.Owner} has {acc.Balance}");
class Account
{
public string Owner { get; set; }
public int Balance { get; private set; }
public Account(string owner) { Owner = owner; }
public void Deposit(int amount)
{
if (amount > 0)
{
Balance = Balance + amount;
}
}
} A number property that nobody has set yet starts at 0.
guess first
Some sweets go in the bag. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
using System;
var bag = new Bag();
bag.Add(3);
bag.Add(-1);
bag.Add(2);
Console.WriteLine(bag.Sweets);
class Bag
{
public int Sweets { get; private set; }
public void Add(int count)
{
if (count > 0)
{
Sweets = Sweets + count;
}
}
}
your turn
Your turn. Give the dog some properties.
On line 11, give Name a get and a set. On line 12, make the set of Kilometres private, so only walks can change it. Name your dog on line 4, then press run.
output
press run to see what happens
fix it
Someone is sneaking coins in. Fix it!
output
press run to see what happens
- C# says
CS0272on line 5: thesetaccessor ofCoinsis private. Who may change it? - Only code inside
PiggyBankcan setCoins. The class gives you a method for adding coins. - Change line 5 to
piggy.Save(3);, then press run.
nailed it
your data is safe inside its class. :D
- A property has
getandsetaccessors. private setlets only the class change a value.- Methods can check a change before making it.
new words in your collection
- property
- accessor
- private
This lesson isn’t saved. A free account remembers every lesson you finish.