CHASH Tutorial



C# ACCESS MODIFIERS


Access Modifiers in C#

Access modifiers in C# define the visibility and scope of classes, methods, variables, and other members. They help protect data and enforce encapsulation.

🔐 Why use access modifiers?
To control who can access what part of your code. This improves security, structure, and reduces bugs.

Types of Access Modifiers

Modifier Description
public Accessible from anywhere (inside or outside the class/project)
private Accessible only within the same class
protected Accessible within the class and by derived classes
internal Accessible only within the same assembly (project)
protected internal Accessible in the same assembly and from derived classes in other assemblies
private protected Accessible within the same class and derived classes in the same assembly

Example: Access Modifiers in Action

class Car
{
    public string brand = "Toyota";        // Can be accessed from anywhere
    private string model = "Fortuner";     // Can only be accessed inside Car
    protected int speed = 100;             // Accessible in derived classes
    internal string fuel = "Diesel";       // Accessible only within this project
}
  

Usage in Derived Class

class SUV : Car
{
    public void Display()
    {
        Console.WriteLine(brand);  // ✅ Accessible (public)
        // Console.WriteLine(model); ❌ Not accessible (private)
        Console.WriteLine(speed);  // ✅ Accessible (protected)
    }
}
  
Best Practice Tip: Use private or protected by default and increase visibility only when required. This keeps your code safe and maintainable.

Quick Summary

  • public: Everywhere
  • private: Inside the class only
  • protected: Inside the class and its children
  • internal: Same assembly/project
  • protected internal: Same project + children in other projects
  • private protected: Same class + derived in same project

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review