Access Modifiers in C#

What are Access Modifiers?

Access modifiers in C# define the visibility and accessibility of classes, methods, and other members. They control how the members of a class can be accessed from other classes and objects.

Types of Access Modifiers in C#

  • public: Accessible from any other class or assembly.
  • private: Accessible only within the same class.
  • protected: Accessible within its own class and by derived class instances.
  • internal: Accessible only within the same assembly.
  • protected internal: Accessible within its own assembly or from derived classes.
  • private protected: Accessible within its containing class or derived classes within the same assembly.

Public Access Modifier

The public access modifier allows members of a class to be accessed from any other class or assembly.

Example of Public Access Modifier:

public class Car
{
    public string model;

    public void DisplayModel()
    {
        Console.WriteLine($"Model: {model}");
    }
}

// Usage
Car car = new Car();
car.model = "Toyota";
car.DisplayModel();  // Accessible from outside the class
        

In this example, the model field and DisplayModel method are marked as public, allowing them to be accessed outside the Car class.

Private Access Modifier

The private access modifier restricts access to members within the same class only.

Example of Private Access Modifier:

public class Car
{
    private string model;

    public void SetModel(string model)
    {
        this.model = model;
    }

    public void DisplayModel()
    {
        Console.WriteLine($"Model: {model}");
    }
}

// Usage
Car car = new Car();
car.SetModel("Honda");  // Can set model via public method
car.DisplayModel();  // Cannot directly access private member
        

In this example, model is private, and it can only be accessed or modified via the public methods SetModel and DisplayModel.

Protected Access Modifier

The protected access modifier allows access within its own class and derived class instances.

Example of Protected Access Modifier:

public class Vehicle
{
    protected string model;

    public void SetModel(string model)
    {
        this.model = model;
    }
}

public class Car : Vehicle
{
    public void DisplayModel()
    {
        Console.WriteLine($"Model: {model}");  // Accessible in derived class
    }
}

// Usage
Car car = new Car();
car.SetModel("Ford");
car.DisplayModel();
        

In this example, model is protected, meaning it can only be accessed from within the Vehicle class or its derived class Car.

Key Points to Remember

  • Access modifiers control the visibility and accessibility of class members.
  • public members can be accessed from anywhere.
  • private members are accessible only within the class they are declared in.
  • protected members are accessible within their class and derived classes.
  • Other modifiers like internal and protected internal control access within the same assembly.