Skip to content

Access Modifiers

Access modifiers control which code can see and use a class, method, or field. The main ones: public (accessible from anywhere), private (only within the same class β€” the default if you write nothing), protected (the class and its subclasses), internal (anywhere in the same assembly/project), and protected internal / private protected (combinations of the above).

public class BankAccount
{
private decimal _balance; // only this class can touch it directly
protected string AccountType; // this class and subclasses
internal string InternalNotes; // anywhere in this project
public decimal GetBalance() => _balance; // anyone can call this
public void Deposit(decimal amount)
{
if (amount <= 0)
throw new ArgumentException("Deposit must be positive");
_balance += amount; // internal state, only modified through this method
}
}
public class SavingsAccount : BankAccount
{
public void PrintType() => Console.WriteLine(AccountType); // OK -- protected, visible to subclass
// public void PrintBalance() => Console.WriteLine(_balance); // Error: _balance is private to BankAccount
}

Making fields public for convenience instead of exposing controlled access through a property or method β€” this lets any external code set the field to an invalid value, bypassing whatever validation logic you intended.

public class BankAccount
{
public decimal Balance; // anyone can do account.Balance = -1000; β€” no validation possible
}
// Better: keep the field private, expose validated access
public class BankAccount
{
private decimal _balance;
public decimal Balance => _balance; // read-only from outside
public void Deposit(decimal amount)
{
if (amount <= 0) throw new ArgumentException("Must be positive");
_balance += amount;
}
}
  1. What’s the default access level for a class member if you write no modifier at all?

    Answerprivate.
  2. What’s the difference between private and protected?

    Answerprivate members are visible only within the declaring class; protected members are also visible to derived (subclass) types.
  3. Why is exposing a field as public generally worse than exposing it through a public property with a private setter?

    AnswerA public field lets any external code assign any value with no validation; a property (even a simple one) gives you a single controlled point where you can add validation, logging, or change the implementation later without breaking callers.