← Back to C# Course | Chapter 6: OOP Basics | Lesson 5 of 7

Access Modifiers

Access modifiers decide who can use something, like rooms in a house with different locks. Public is open to all, private is just for the class itself.

In this page:

  1. Access Modifiers
Syntax
csharp
class ClassName
{
    public type A;      // anywhere
    private type B;     // this class only
    protected type C;   // this class and derived classes
    internal type D;    // this assembly
}

Access Modifiers

Access modifiers (public, private, protected, internal) control which code can see a class member.

public members are visible everywhere, private members only inside the declaring class, and protected members inside the class and its subclasses. Encapsulating fields as private and exposing them through public properties is a core OOP practice.

Warning: Class members are private by default in C# if you omit a modifier.

Example: Access Modifiers

markup
using System;

class Account
{
    private decimal balance;

    public Account(decimal startingBalance)
    {
        balance = startingBalance;
    }

    public void Deposit(decimal amount)
    {
        balance += amount;
    }

    public decimal GetBalance()
    {
        return balance;
    }
}

class Program
{
    static void Main(string[] args)
    {
        Account acc = new Account(100);
        acc.Deposit(50);
        Console.WriteLine(acc.GetBalance());
    }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Leaving members with the default private access and getting 'inaccessible due to its protection level' errors.
  2. Making every member public, which breaks encapsulation.
  3. Using protected and expecting access from unrelated classes.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.