Methods on a Class

Write instance methods that use and change an object's state safely, keep its rules inside the class, and know when a method should be static.

Apprentice · C# · OOP · Updated

By

After this lesson you can

  • Write methods that use and change an object's state, keeping its rules inside the class

Key takeaways

  • Put each rule inside the class that owns the data, and give the data a private set, so only the class's methods can change it.
  • A class's methods can call each other and use its properties without naming an object, as Withdraw calls CanWithdraw.
  • An instance method reads or changes one object's state; a static method belongs to the class and needs only its parameters.
  • const makes a value that never changes, such as MaxPaper, and constants are named in PascalCase.

Properties hold what an object knows; methods are what it does. A class's methods are where its rules live: what's allowed, what changes together, and what happens when something can't be done.

A method that changes state, with rules

A printer has paper and toner. Printing uses one sheet and one unit of toner per copy, and it can't print more than it has. That rule belongs inside the Printer class, so no code anywhere can get it wrong:

Printer printer = new Printer(paper: 10, toner: 100);

int printed = printer.Print(4);
Console.WriteLine(quot;Printed {printed}, {printer.Paper} sheets left");

printed = printer.Print(25);
Console.WriteLine(quot;Printed {printed}, {printer.Paper} sheets left");

printer.AddPaper(800);
Console.WriteLine(quot;After adding paper: {printer.Paper} sheets");

public class Printer
{
    public const int MaxPaper = 500;

    public int Paper { get; private set; }
    public int Toner { get; private set; }

    public Printer(int paper, int toner)
    {
        Paper = paper;
        Toner = toner;
    }

    // Prints as many copies as the paper and toner allow, and returns how many.
    public int Print(int copies)
    {
        if (copies <= 0)
        {
            return 0;
        }

        int possible = Math.Min(Paper, Toner);
        int printed = Math.Min(copies, possible);

        Paper -= printed;
        Toner -= printed;
        return printed;
    }

    public void AddPaper(int sheets)
    {
        Paper = Math.Min(Paper + sheets, MaxPaper);
    }
}
Printed 4, 6 sheets left
Printed 6, 0 sheets left
After adding paper: 500 sheets
  • Paper and Toner have private set, so the only way to change them is through Print and AddPaper, which follow the rules.
  • Math.Min returns the smaller of two numbers.
  • const makes MaxPaper a value that never changes. Constants are named in PascalCase.
  • new Printer(paper: 10, toner: 100) names each argument. It's optional, but it makes calls with several numbers easy to read.

Methods can use each other

Methods in a class can call each other, and use the class's properties, without naming an object: they work on the same object.

BankAccount account = new BankAccount("Ana", 100m);
account.Withdraw(30m);
account.Withdraw(500m);
Console.WriteLine(account.Summary());

public class BankAccount
{
    public string Owner { get; }
    public decimal Balance { get; private set; }

    public BankAccount(string owner, decimal openingBalance)
    {
        Owner = owner;
        Balance = openingBalance;
    }

    public bool CanWithdraw(decimal amount) => amount > 0 && amount <= Balance;

    public bool Withdraw(decimal amount)
    {
        if (!CanWithdraw(amount))
        {
            return false;
        }
        Balance -= amount;
        return true;
    }

    public string Summary() => quot;{Owner} has {Balance:C}";
}
Ana has $70.00

Withdraw calls CanWithdraw, and the $500 withdrawal is refused because the balance would go below zero.

Instance or static?

The methods in this lesson are instance methods: they belong to one object and use its state. account.Withdraw(30m) changes that account.

A static method, like the ones you wrote in the Methods chapter, belongs to the class itself and uses no object's state. You call it with the class's name: Math.Min(3, 7). A good test: if a method needs to read or change an object's properties, it's an instance method. If it only needs its parameters, it can be static.

Console.WriteLine(Temperature.ToCelsius(212));

public static class Temperature
{
    public static double ToCelsius(double fahrenheit) => (fahrenheit - 32) * 5 / 9;
}
100

Do it: sell tickets at the booth, by the rules

The basketball league's ticket booth sells seats for Saturday's game. It has two rules: one order can be at most 6 tickets, and it can't sell more seats than it has left. Keep both rules inside the class, so no code anywhere can sell a seat that isn't there.

The class TicketBooth gets two values:

  • seats: how many seats the booth starts with, an int, given to the constructor (20).
  • tickets: how many tickets one order asks for, an int, given to CanSell and Sell (6).

The starter has the constant MaxPerOrder, which is 6, and the property SeatsLeft, which only the class can set.

For example:

TicketBooth booth = new TicketBooth(20);
booth.Sell(6);
booth.Sell(7);
Call Returns Why SeatsLeft after it
new TicketBooth(20) the booth starts with 20 seats 20
Sell(6) true 6 is at most 6, and 20 seats are left 14
Sell(7) false 7 is more than 6 in one order, so nothing changes 14

So after these calls, booth.SeatsLeft is 14.

Your job: finish the class TicketBooth.

  • The constructor stores seats in SeatsLeft.
  • CanSell(int tickets) returns true when tickets is more than 0, at most MaxPerOrder, and at most SeatsLeft. Otherwise it returns false. It changes nothing.
  • Sell(int tickets) calls CanSell. When the answer is true, it takes the tickets away from SeatsLeft and returns true. When it's false, it returns false and changes nothing.

Practiced live on the lesson page: write the C# right there and check it.

Check yourself

2 questions to try on the lesson page.

So what

An object's methods are its rules in action. Put each rule inside the class that owns the data, keep the data's set private, and every part of the program gets the rule right for free.

Key terms

Cheat sheets