Access Modifiers
Access Modifiers
Section titled βAccess ModifiersβWhat it means
Section titled βWhat it meansβ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).
Examples
Section titled βExamplesβ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}Common mistake
Section titled βCommon mistakeβ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 accesspublic 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; }}Quick practice
Section titled βQuick practiceβ-
Whatβs the default access level for a class member if you write no modifier at all?
Answer
private. -
Whatβs the difference between
privateandprotected?Answer
privatemembers are visible only within the declaring class;protectedmembers are also visible to derived (subclass) types. -
Why is exposing a field as
publicgenerally worse than exposing it through a public property with a private setter?Answer
A 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.