Learn Access Modifiers in C#

C#Accessmofidiers

What are Access Modifiers?

Access modifiers are simply keywords which are used to give accessibility permissions to classes methods and other members in object oriented programming. In this article we will discuss about access modifiers which are used in C# programming language.

What is the Use of Access Modifiers?

Simply the use of access modifiers are to give permission levels for programs to access other classes, methods and other members(such as variables). If you don’t want a variable, method or class to be accessed by every other members in your program you can use access modifiers to restrict and control the accessibility.

How Many Access Modifiers are there in C#?

In C# there are 6 access modifiers that we can use

  1. Public
  2. Private
  3. Protected
  4. Internal
  5. Protected Internal
  6. Private protected

1.Public

If you declare a field using public access modifier that particular field is accessible for all the classes in the system. Therefore public access modifiers has the most permissive access level. You can access it without any restriction

class Child
{
  public string Name= "Mike";
}

class Parent
{
  static void Main(string[] args)
  {
    Child myChild= new Child();
    Console.WriteLine(myChild.Name);
  }
}

Here you can see two different classes as Child and Parent. Name property in the child class is declared public so the Name property can be accessed from anywhere in the project. How ever in here I have called it from another class called Parent.

if we change the public keyword(access level) in child class to private or protected. After that we cant access the Name property as shown above. We will be inaccessible with a protection level error message.

2.Private

We use private key word to specify the the private access modifier. What we have to remember is if we declare methods, variables or members using private access modifier those members can be only accessible within the same class which they were declared.

Therefore Any other classes in the project cannot get access to private declared members.

class Student
{
    private string name = "FirstName, LastName";
    private string id="785269845V";
    public string GetName()
    {
        return name;
    }
    public string GetId
    {
        get { return id; }
    }
}

class Teacher
{
    static void Main()
    {
        var e = new Student();

        // The data members are inaccessible from this class directly(private)
        // they can't be accessed like this:
        //    string n = e.name;
        //    string s = e.id;
        // 'name' is indirectly accessed via methods
        // using public method GetName 
        string n = e.GetName();

        // 'id' can be indirectly accessed via methods
       // Using public method GetId
        string s = e.GetId;
    }
}

In the above code block we cant directly access variables declared as private from a outside class (Student class). The below diagram green color arrows shows the correct method to access private variables from a different class. Software developers use this method to access private variables through public classes.

3.Protected

Members we declare using protected key word can only be accessed within its class and the classes derived from that class. In other words, protected variables can only be accessed by it’s own class and its sub classes.

class BankAccount
{
    protected int pass = 123;
}

class SavingsAccount : BankAccount
{
    static void Main()
    {
        var a = new BankAccount();
        var b = new SavingsAccount ();

        // Error CS1540, because x can only be accessed by
        // classes derived from BankAccount.
        // a.pass = 10;

        // OK, because this class derives from BankAccount.
        b.pass = 10;
    }
}

In the above code a.pass generates an error. We can access protected variables only from inside the BankAccount class or from a instance of a class which derives from BankAccount class(Savings Account). Here class a is a direct instance of the BankAccount class. So Class a cannot access variable pass using a.pass.

Above all, a key point you should remember is that protected members can only be accessed through inheritance.

4.Internal

Internal types and members are only accessible within the same assembly.

What is a assembly in C#?

Assembly is a kind of file where you have your compiled code. There are 2 types of assemblies as process assembly(.exe) and library assembly(.dll). In practicality a single software project consist with different other sub projects which are developed by other programmers which run on different assemblies.
You can access internal access modifier members from any class in the same assembly

// Assembly1.cs  
// Compile with: /target:library  
internal class BaseClass
{  
   public static int intM = 0;  
}


// Assembly1_a.cs  
// Compile with: /reference:Assembly1.dll  
class TestAccess
{  
   static void Main()
   {  
      var myBase = new BaseClass();   // CS0122  
   }  
}

Here from the ‘file Assembly1_a.cs you cannot access a internal method or initiate a internal method which is compiled in Assembly1.cs. Because the compiler has compiled these 2 files as separate .dll s 

Example 2


// Assembly2.cs  
// Compile with: /target:library  
public class BaseClass
{  
   internal static int intM = 0;  
}


// Assembly2_a.cs  
// Compile with: /reference:Assembly2.dll  
public class TestAccess
{  
   static void Main()
   {  
      var myBase = new BaseClass();   // Ok.  
      BaseClass.intM = 444;    // CS0117  
   }  
}

From the Assembly2_a.cs file you can access the BaseClass method as it’s declared as public. But you cannot access the internal member intM from the Assembly2_a.cs file. Because that’s a internal variable which is compiled in a separate assembly from the calling project.

5.Protected internal

Members declared in the protected internal access modifier can be accessed from anywhere within the containing assembly and from within a derived class in any other assembly. If a class is inherited from another class which has internal members those members can be accessed from a external  assembly using a class derived from the previous class.

// Assembly1.cs
// Compile with: /target:library
public class MyClass
{
   protected internal string color= "";
}

class gradeone
{
    void Access()
    {
        var newObject = new MyClass();
        newObject.color= "Yellow";
    }
}

protected internal members can be accessed from any type within it’s containing assembly. So no problem that newObject can access the color property.

// Assembly2.cs
// Compile with: /reference:Assembly1.dll
class DerivedClass : MyClass
{
    static void Main()
    {
        var baseObject = new MyClass();
        var derivedObject = new DerivedClass();

        // Error CS1540, because color can only be accessed by
        // classes derived from MyClass.
        // baseObject.myValue = "red";

        // OK, because this derivedObject class derives from MyClass.
        derivedObject.color = "Green";
    }
}

in the above code baseObject.myValue = "Red"; creates and error because baseObject class is not derived from the MyClass, It’s a direct instance of the MyClass. To be able to access a protected internal member it should be accessed through a derived class type.

6.Private protected

First thing is that Private protected members can be accessed only within same assembly. And types that access private protected members should be derived from the containing class.

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

public class DerivedClass1 : BaseClass
{
    void Access()
    {
        var baseObject = new BaseClass();

        // Error CS1540, because myValue can only be accessed by
        // classes derived from BaseClass.
        // baseObject.myValue = 5;

        // OK, accessed through the current derived class instance
        myValue = 5;
    }
}

Here baseObject.myValue gives an error because it’s directly an instance of the BaseClass. To be able to access private protected methods in BaseClass it should be accessed through a class which derives from BaseClass and should be from the same assembly.

The below code is from a different assembly Assembly2.cs

// Assembly2.cs
// Compile with: /reference:Assembly1.dll
class DerivedClass2 : BaseClass
{
    void Access()
    {
        // Error CS0122, because myValue can only be
        // accessed by types in Assembly1
        // myValue = 10;
    }
}

Here myValue cannot be accessed even from a derived class as the code is in a different assembly.

Reference Materials
Microsoft C# Documentation
W3 Schools

Leave a Reply

Your email address will not be published. Required fields are marked *