.NET  

Learn Access Modifiers in C#

Access modifiers in C# are keywords used to define the accessibility or visibility of classes, methods, variables, and other members. They help control how and where these members can be accessed. Here's a concise overview of the main access modifiers in C#:

1. Public

  • Description: Accessible from anywhere in the program.
  • Use Case: When you want a member to be universally accessible.
  • Example
    public class MyClass
    {
        public int MyProperty { get; set; }
    }
    

2. Private

  • Description: Accessible only within the containing class.
  • Use Case: To encapsulate data and prevent external access.
  • Example
    public class MyClass
    {
        private int myField;
    }
    

3. Protected

  • Description: Accessible within the containing class and by derived classes.
  • Use Case: When you want to allow access to subclasses but not to other classes.
  • Example
    public class MyClass
    {
        protected int myField;
    }
    

4. Internal

  • Description: Accessible only within the same assembly.
  • Use Case: To restrict access to the same project or library.
  • Example
    internal class MyClass
    {
        internal int MyProperty { get; set; }
    }
    

5. Protected Internal

  • Description: Accessible within the same assembly or by derived classes in other assemblies.
  • Use Case: A combination of protected and internal access.
  • Example
    public class MyClass
    {
        protected internal int myField;
    }
    

6. Private Protected

  • Description: Accessible within the containing class or derived classes in the same assembly.
  • Use Case: To limit access to derived classes within the same assembly.
  • Example
    public class MyClass
    {
        private protected int myField;
    }
    

Summary Table

Modifier Same Class Derived Class Same Assembly Other Assemblies
public
private
protected
internal
protected internal ✔ (if derived)
private protected

These modifiers are essential for implementing encapsulation and controlling access to your code effectively.