Skip to main content
CSharpUniversity ASP.NET and C# lessons

The search runs entirely in your browser over the published lesson list.

A second class, with more detail

Your second class is where the shape of a good class becomes clear: it holds its own data, guards its own rules and offers a small set of useful methods.

A class that sets itself up

C#
public class BankAccount
{
    private double balance;

    public BankAccount(double opening)
    {
        balance = opening;
    }

    public void Deposit(double amount)
    {
        if (amount > 0)
        {
            balance = balance + amount;
        }
    }

    public double Balance()
    {
        return balance;
    }
}

What is better here

  • The constructor sets a sensible starting value, so no object begins in a broken state.
  • The deposit method refuses a negative amount, so the rule lives with the data.
  • The balance can be read but not set directly from outside.
One responsibility. A class should have one reason to change. If you struggle to describe what a class does in one sentence, split it.

Related to this is a question you will meet constantly: where a variable can be seen.

New lessons by email

Leave your address and get a short note whenever a fresh lesson is published. No account needed and you can stop at any time.

Thank you. Your address has been noted in this browser session. Connect a mailing service to deliver the notes for real.