Access Modifiers in C#

Access Modifiers are keywords that define the accessibility of a member, class or datatype in a program. These are mainly used to restrict unwanted data manipulation by external programs or classes. There are 4 access modifiers (public, protected, internal, private) which defines the 6 accessibility levels as follows:

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

Why to use access modifiers?

Access modifiers are an integral part of object-oriented programming. It are used to implement encapsulation of OOP. Access modifiers allow you to define who does or who doesn’t have access to certain features.

  • public: The type or member can be accessed by any other code in the same assembly or another assembly that references it.
  • private: The type or member can be accessed only by code in the same class or struct.
  • protected: The type or member can be accessed only by code in the same class, or in a class that is derived from that class.
  • internal: The type or member can be accessed by any code in the same assembly, but not from another assembly.
  • protected internal: The type or member can be accessed by any code in the assembly in which it’s declared, or from within a derived class in another assembly.
  • private protected: The type or member can be accessed only within its declaring assembly, by code in the same class or in a type that is derived from that class.
Private Access Modifier

The scope of the accessibility is limited only inside the classes or struct in which they are declared. The private members cannot be accessed outside the class and it is the least permissive access level .

using System;
namespace ConsoleApplication1
{
  class PrivateAccess
  {
    private string msg = "This variable is private ";
    private void disp(string msg)
    {
      Console.WriteLine("This function is private : " + msg);
    }
  }
  class Program
  {
    static void Main(string[] args)
    {
      PrivateAccess privateTest = new PrivateAccess();
      Console.WriteLine(privateTest.msg);// Cannot Access private variable here
      privateTest.disp("Hello !!");  // Cannot Access private function  here
    }
  }
}
Public Modifier

If you declare a field with a public access modifier, it is accessible for all classes.

The public keyword is an access modifier for types and type members. Public access is the most permissive access level. There are no restrictions on accessing public members.

class Car
{
  public string model = "Mustang";
}

class Program
{
  static void Main(string[] args)
  {
    Car myObj = new Car();
    Console.WriteLine(myObj.model);
  }
}
Protected Access Modifier

The protected keyword implies that the object is accessible inside the class and in all classes that derive from that class. We will talk in more detail about inheritance in module 2 about object-oriented programming. But for now, we are going to take a look at this example to understand the behavior of the protected members:

class NumberClass
{
    protected int number = 10; //we can access this variable inside this class
}

class DerivedClass: NumberClass //this is inheritance. DerivedClass derives from the NumberClass class
{
    void Print()
    {
        Console.WriteLine(number); //we can access it in this class as well because it derives from the NumberClass class
    }
}

class Program
{
    void Print()
    {
        NumberClass num = new NumberClass();
        Console.WriteLine(num.number); // Error. The number variable is inaccessible due to its protection level. 
                               // The Program class doesn't derive from the NumberClass
    }
}
Internal Access Modifier

The internal access modifiers can access within the program that contain its declarations and also access only within files in the same assembly level but not from another assembly.

using System;
namespace ConsoleApplication1
{
  class InternalAccess
  {
    internal string msg = "This variable is internal";
    internal void disp(string msg)
    {
      Console.WriteLine("This function is internal : " + msg);
    }
  }
  class Program
  {
    static void Main(string[] args)
    {
      InternalAccess iAccess = new InternalAccess();
      Console.WriteLine(iAccess.msg); // Accessing internal variable
      iAccess.disp("Hello !!"); // Accessing internal function
      Console.ReadKey();
    }
  }
}
Protected Internal Access Modifier

The protected internal access modifier is a combination of protected and internal. As a result, we can access the protected internal member only in the same assembly or in a derived class in other assemblies (projects):

//First Project (ASSEMBLY)
public class NumberClassInFirstProject
{
    protected internal int number = 10; //we can access this variable inside this class
}

class ProgramInFirstProject
{
    void Print()
    {
        NumberClassInFirstProject num = new NumberClassInFirstProject();
        Console.WriteLine(num.number); // This is OK. Anywhere in this project (assembly) we can access the number variable.
    }
}

//Second project (ASSEMBLY)
class Program: NumberClassInFirstProject //Inheritance
{
    void Print()
    {
        Console.WriteLine(number); //This is OK as well. The class Program derives from the NumberClassInFirstProject class.
    }
}
Private Protected Access Modifier

Access is granted to the containing class and its derived types present in the current assembly. This modifier is valid in C# version 7.2 and later. C# version 7.2 and later , the new modifier private protected really means protected AND also internal. That is – member is accessible only to child classes which are in the same assembly, but not to child classes which are outside assembly (so restriction implied by “protected” is narrowed – becomes even more restrictive). That is useful if you build hierarchy of classes in your assembly and do not want any child classes from other assemblies to access certain parts of that hierarchy.

using System; 
  
namespace PrivateProtectedAccessModifier { 
  
class Parent { 
  
    // Member is declared as private protected 
    private protected int value; 
  
    // value is Accessible only inside the class 
    public void setValue(int v) 
    { 
        value = v; 
    } 
    public int getValue() 
    { 
        return value; 
    } 
} 
  
class Child : Parent { 
  
    public void showValue() 
    { 
        // Trying to access value 
        // Inside a derived class 
  
        Console.WriteLine("Value = " + value); 
        // value is accesible 
    } 
} 
  
// Driver Code 
class Program { 
  
    // Main Method 
    static void Main(string[] args) 
    { 
        Parent obj = new Parent(); 
  
        // obj.value = 5; 
        // Also gives an error 
  
        // Use public functions to assign 
        // and use value of the member 'value' 
        obj.setValue(4); 
        Console.WriteLine("Value = " + obj.getValue()); 
    } 
} 
} 
0 0 votes
Article Rating

Do you want to hire us for your Project Work? Then Contact US.
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x