×

c# · level 2 · unit 2 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.