Sobes.tech
Junior — Middle

What are the main differences between access modifiers public, private, and protected in programming languages?

sobes.tech AI

Answer from AI

In C#, access modifiers define the visibility of class members:

  • public: accessible from any code, without restrictions.
  • private: accessible only within the same class or structure.
  • protected: accessible within the same class and in derived classes.

Example:

class BaseClass {
    public int PublicField;
    private int PrivateField;
    protected int ProtectedField;

    void Method() {
        // Access to all fields within the class
        PublicField = 1;
        PrivateField = 2;
        ProtectedField = 3;
    }
}

class DerivedClass : BaseClass {
    void Method() {
        PublicField = 1;      // Accessible
        // PrivateField = 2;  // Error, not accessible
        ProtectedField = 3;   // Accessible
    }
}

Thus, private is the most restrictive, protected extends access to descendants, and public is fully open.

What are the main differences between access… - sobes.tech