Tool for HR, Hiring Managers, and the Leadership Team

What are Access Specifiers in C#?

Access Specifiers in C# are used to control the visibility (accessibility) of classes, methods, properties, and variables.

They define who can access what in your code.

🔹 Types of Access Specifiers in C#

There are 6 Access Specifiers in C#:

Access Specifier Accessible From
public Anywhere
private Within same class only
protected Same class + derived class
internal Same project (assembly)
protected internal Same project OR derived class
private protected Same class + derived class (same project only)

🔹 1. Public

Accessible from anywhere

public class Employee
{
    public string Name;
}

Usage:

Employee emp = new Employee();
emp.Name = "Sampath";

✅ Accessible everywhere

🔹 2. Private

Accessible only inside the same class

public class Employee
{
    private int salary;

    public void SetSalary(int amount)
    {
        salary = amount;
    }
}

❌ Cannot access outside class

🔹 3. Protected

Accessible:

  • Same class

  • Derived class

public class Animal
{
    protected void Eat()
    {
        Console.WriteLine("Eating...");
    }
}

public class Dog : Animal
{
    public void Test()
    {
        Eat(); // Allowed
    }
}

🔹 4. Internal

Accessible within same project

internal class Employee
{
    public string Name;
}

✅ Same project → Allowed
❌ Different project → Not allowed

🔹 5. Protected Internal

Accessible:

  • Same project

  • Derived class (even different project)

protected internal void Test()
{
}

🔹 6. Private Protected

Accessible:

  • Same class

  • Derived class within same project only

private protected void Test()
{
}

🔹 Default Access Specifier

Type Default
Class internal
Method private
Variable private

🔹 Real World Example

public class BankAccount
{
    public string AccountHolder;
    private decimal Balance;

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

    public decimal GetBalance()
    {
        return Balance;
    }
}

Here:

  • AccountHolder → Public

  • Balance → Private (secure)

  • Deposit() → Public

🔹 Interview One-Line Answer 

Access Specifiers control the visibility of class members and define where they can be accessed.

🔹 Very Common Interview Question

Which is most restrictive?

👉 private

Which is least restrictive?

👉 public

🔹 Easy Way to Remember

private → Only me
protected → Me + children
internal → My project
public → Everyone