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

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

Public and private members

Not everything inside a class should be reachable from outside. Access modifiers draw that line.

The two you will use most

  • public. Other code can call it. This is the class's promise to the rest of the program.
  • private. Only the class itself can use it. This is the class's own business.
C#
public class Counter
{
    private int total = 0;

    public void AddOne()
    {
        total = total + 1;
    }

    public int Current()
    {
        return total;
    }
}

Why hide anything

A private field cannot be changed by careless code elsewhere. The class stays in control of its own values, which makes bugs easier to find because there are fewer places they can start.

Default to private. Make something public only when another part of the program genuinely needs it. You can always open access later; closing it after others depend on it is much harder.

A cleaner way to expose a value is a property, covered later in this track.

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.