Access Modifiers: public, private, and protected

Controlling access to your code

Posted by Rodrigo Castro on November 16, 2024

Access modifiers decide who can see and use parts of your code.

public

Anyone can access.

1
2
3
4
public class Car
{
    public string Model; // Anyone can read/write Model
}

private

Only the class itself can access.

1
2
3
4
class BankAccount
{
    private decimal balance; // Only code inside BankAccount can see this
}

protected

The class and its children can access.

1
2
3
4
5
6
7
8
class Animal
{
    protected void Sleep() { /* ... */ }
}
class Cat : Animal
{
    public void Nap() { Sleep(); }
}

The internal Access Modifier

In addition to public, private, and protected, C# provides the internal access modifier.

What is internal?

  • internal members are accessible only within the same assembly (project).
  • They are not accessible from another assembly, even if referenced.
  • Commonly used for code that should be visible throughout a project, but hidden from external code or consumers (such as library users).

Example

1
2
3
4
5
6
7
internal class InternalClass
{
    internal void DoSomething()
    {
        Console.WriteLine("This is only accessible within the same assembly.");
    }
}

You can also combine protected and internal:

  • protected internal — accessible from the same assembly or from derived classes.
  • private protected — accessible only from derived classes within the same assembly.

Access Modifier Summary Table

Modifier Accessible Within Class Derived Class (Same Assembly) Derived Class (Other Assembly) Same Assembly Other Assembly
private ✔️        
protected ✔️ ✔️ ✔️    
internal ✔️ ✔️   ✔️  
public ✔️ ✔️ ✔️ ✔️ ✔️
protected internal ✔️ ✔️ ✔️ ✔️  
private protected ✔️ ✔️   ✔️  

📝 Summary Table

Modifier Who Can Access?
public Anyone
private Only this class
protected This class + subclasses

Tip: Use the smallest possible access for safety.

Next: Working with generics in C#!