C# Exception Handling
C# File I/O
C# Delegates and Events
C# Generics
C# Async Programming
C# Access Modifiers

C# Access Modifiers

Access modifiers control what code can see and use a class member.

1 - The Modifiers

  • public — accessible from anywhere
  • private — accessible only within the same class (default for members)
  • protected — accessible within the class and derived classes
  • internal — accessible within the same assembly
  • protected internal — accessible from the same assembly OR derived classes
  • private protected — derived classes within the same assembly only

2 - Example

public class BankAccount
{
    public  string  Owner   { get; }      // anyone
    private decimal _balance;             // this class only
    private string  _pin;

    public decimal Balance => _balance;   // read-only to outside

    public BankAccount(string owner, decimal initial, string pin)
    {
        Owner    = owner;
        _balance = initial;
        _pin     = pin;
    }

    public bool Withdraw(decimal amount, string pin)
    {
        if (!VerifyPin(pin)) return false;
        if (amount > _balance) return false;
        _balance -= amount;
        return true;
    }

    private bool VerifyPin(string pin) =>
        string.Equals(_pin, pin, StringComparison.Ordinal);
}

3 - Property-Level Modifiers

public class User
{
    public string Name { get; private set; } // public read, private write
    public string Role { get; protected set; }

    public void ChangeName(string newName) => Name = newName; // allowed inside class
}

Note: Default to private for all fields and methods. Only make members public when external code genuinely needs them. Minimising the public surface area makes refactoring safer.

-Tip-