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
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
WithdrawcallsCanWithdraw. - An instance method reads or changes one object's state; a
staticmethod belongs to the class and needs only its parameters. constmakes a value that never changes, such asMaxPaper, 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
PaperandTonerhaveprivate set, so the only way to change them is throughPrintandAddPaper, which follow the rules.Math.Minreturns the smaller of two numbers.constmakesMaxPapera 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
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.