Access modifiers in C#

Photo by Kyle Glenn on Unsplash

Access modifiers in C#

Access modifiers are basically keywords that set the access or level of visibility on classes, methods, variables in our code. In other words if a class, method, variable can be used or be accessed from code of its assembly or other assemblies.

Type of access modifiers

There are currently six base types of access modifiers in C#.

  • public
  • private
  • protected
  • internal
  • protected internal
  • private protected

    The public access modifier

    Probably the most famous one. When we declare a class as public then it can be accessed from any class.
    public class PublicClass
    {
      // Some awesome staff here...
    }
    

    The private access modifier

    Properties or methods that are declared as private can be accessed only within the specific class or struct
    public class PublicClass
    {
      private void string PrivateMethod()
      {
          // do great things here
      }    
    }
    

    The protected access modifier

    Properties or methods that are declared as protected can be accessed only by code in the same class or in a class that is derived from that class.
public class ParentClass
{
    protected int _protectedInt;
}

public class DerivedClass: ParentClass
{
    static void Main()
    {
        var derivedClass = new DerivedClass();

        // Direct access to protected members.
        derivedClass._protectedInt = 10;
    }
}

The internal access modifier

Types or members can be accessed from anywhere inside the same assembly but not from other assemblies

internal class InternalClass
{
    // Our hello world code here
}

The protected internal access modifier

A protected internal member is accessible from the current assembly or from types that are derived from the containing class.

public class AssemblyOneBaseClass
{
   protected internal int someInt = 0;
}

public class AssemblyOneTestClass
{
    void Access()
    {
        var assemblyOneBaseClass = new AssemblyOneBaseClass();
        assemblyOneBaseClass.someInt = 5;
    }
}

public class AssemblyTwoDerivedClass : AssemblyOneBaseClass
{
    static void Main()
    {
        var assemblyOneBaseClass = new AssemblyOneBaseClass();
        var assemblyTwoDerivedClass = new AssemblyTwoDerivedClass();

        assemblyOneBaseClass.someInt = 10;
    }
}

The private protected access modifier

A private protected member is accessible by types derived from the containing class, but only within its containing assembly.

public class BaseClass
{
    private protected int someInt = 0;
}

public class DerivedClass : BaseClass
{
    void Access()
    {
        var baseClass = new BaseClass();
        someInt = 5;
    }
}

All the above in a glance

prlmzaidpn8pcv7j9gw8.png

Did you find this article valuable?

Support Theodoros Karropoulos by becoming a sponsor. Any amount is appreciated!