CodeBlanks Logo Icon CodeBlanks

Access modifiers

C# course · Intermediate · Lesson 24/116

Learn the differences between public, private, protected and internal.

Access modifiers

Access modifiers control where a class member can be seen. C# has four main modifiers: public from anywhere, private only inside the class, protected from the class and its derived classes, internal from within the same assembly.

The default modifier for class members is private. So if you do not write public explicitly, the member is not accessible outside the class. For encapsulation, most fields are private and exposed through public properties.

protected and internal

protected makes a member accessible from within the class and from derived subclasses. It is ideal for members that subclasses should see but the outside world should not.

internal makes a member accessible from anywhere within the same assembly. If you write a library, classes inside the library see each other, but code outside does not. Combining both, protected internal allows access from either the same assembly or a derived class.

Exercise Use a private field in the Account class

Define an Account class. Add a private decimal balance; field. Add a public void Deposit(decimal amount) method with balance = balance + amount; in the body. Also add a public decimal GetBalance() method with return balance;. Inside Main call Deposit(100) and print GetBalance().

Show example solution
Add a private balance field, Deposit and GetBalance methods to Account. In Main write Account a = new Account(); a.Deposit(100); Console.WriteLine(a.GetBalance());
Example solution:
using System;

class Account
{
    private decimal balance;

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

    public decimal GetBalance()
    {
        return balance;
    }
}

class Program
{
    static void Main()
    {
        Account a = new Account();
        a.Deposit(100);
        Console.WriteLine(a.GetBalance());
    }
}

Test yourself

  1. Which allows access only from within the class?

    • public
    • internal
    • private
    • protected
    Show answer

    private — Correct. private allows access only from within the class.

  2. Complete the private field

    private ____ count;
    Show answer
    private int count;
  3. Match each modifier to its scope

    public
    From anywhere
    private
    Class only
    protected
    Class and subclasses
    internal
    Same assembly

All lessons in Intermediate