2.5.5 Public and Private Access Modifiers

Video: The Private Visibility Modifier (17:39)
Public and Private Access Modifiers

Write C# declarations that express the boundary shown in the Player diagram. The modifier appears on each field or method declaration.

Write mixed visibility in one class
Soccer example
public class Player
{
    private int numberOfTurns;

    public int GetNumberOfTurns()
    {
        return this.numberOfTurns;
    }
}

Place this complete definition in Player.cs for the example. The class is public, the stored integer is private, and the query method is public. The integer starts at 0. The query returns its current value without changing it.

Check access from another class

Place these valid statements inside a method in a different class.

Valid outside access
Player jordan = new Player();
int turns = jordan.GetNumberOfTurns();

The result stored in turns is 0. In contrast, the following line is intentionally invalid in that outside method.

Intentional compile-time error
jordan.numberOfTurns = 2;
Change visibility with evidence

Use Find All References before changing an existing member. A private member can still be used by code inside its declaring class. Outside users must use an appropriate public member or be revised as part of the change.

Do not make every declaration private: the class and useful entry points still need their intended access. Avoid adding a getter automatically for every hidden field.

Apply the idea
Check your understanding