Open In App

C# Access Modifiers

Last Updated : 15 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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. These modifiers control the scope and extent of access to classes, methods, properties, and other members within and from external classes or assemblies. By using modifiers we ensure that certain data or functionality is exposed only when necessary otherwise keep it hidden.

Access Modifiers and Accessibility

There are 4 access modifiers (public, protected, internal, private) which define the 6 accessibility levels as follows:

Modifiers

Entire program

Containing Class

Current assembly

Derived Types

Derived Types within Current Assembly

public

Yes

Yes

Yes

Yes

Yes

private

No

Yes

No

No

No

protected

No

Yes

No

Yes

Yes

internal

No

Yes

Yes

No

Yes

protected internal

No

Yes

Yes

Yes

Yes

protected private

No

Yes

No

No

Yes

1. public Modifier

public modifier provides access to the entire program. It means that another method or another assembly which contains the class reference can access these members or types. This access modifier has the most permissive access level in comparison to all other access modifiers.

Example:

C#
using System;

class Student
{
    public int rollNo;
    public string name;

    public Student(int r, string n)
    {
        rollNo = r;
        name = n;
    }

    public int getRollNo()
    {
        return rollNo;
    }

    public string getName()
    {
        return name;
    }
}

class Geeks
{
    static void Main(string[] args)
    {
        Student S = new Student(1, "Geek");

        // accessible through another method       
        Console.WriteLine("Displaying using class members");
        Console.WriteLine("Roll number: {0}", S.rollNo);
        Console.WriteLine("Name: {0}", S.name);

        Console.WriteLine();

        Console.WriteLine("Displaying Using methods");
        Console.WriteLine("Roll number: {0}", S.getRollNo());
        Console.WriteLine("Name: {0}", S.getName());
    }
}

Output
Displaying using class members
Roll number: 1
Name: Geek

Displaying Using methods
Roll number: 1
Name: Geek

2. private modifier

private access modifier limits access to members of a class so that only the class itself can use them. Private members cannot be accessed from outside the class, not even by derived classes.

Example:

C#
using System;

class Parent 
{	
	private 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 );
		// Gives an error
	}
}

class Geeks 
{
	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());
	}
}

Output
Value = 4

3. protected Modifier

protected access modifier allows members to be accessible within the class and by derived classes (subclasses). It does not allow access from outside the class or its derived classes.

Example:

C#
using System;

class Student 
{  
    protected string name;
  
    public Student(string studentName)
    {
        name = studentName; 
    }
}

class Geek : Student 
using System;

class Student
{
    protected string name;
  
    public Student(string studentName)
    {
        name = studentName; // Initialize name
    }
}


class Geek : Student
{

    public Geek(string geekName) : base(geekName)
    {

    }

    public string GetName()
    { 
      // Access protected member from base class 
        return name; 
    }
}

class Geeks
{
    static void Main(string[] args)
    {

        Geek obj = new Geek("Geeky");

        // Access the protected member through the derived class method
        Console.WriteLine("The student's name is: {0}",
                          obj.GetName());
    }
}
{
    
    public Geek(string geekName) : base(geekName) 
    { 
     
    }
  
    public string GetName()
    { 
      // Access protected member from base class
        return name; 
    }
}

class Geeks 
{
    static void Main(string[] args)
    {
        
        Geek obj = new Geek("Geeky");
        
        // Access the protected member through the derived class method
        Console.WriteLine("The student's name is: {0}", 
                          obj.GetName());
    }
}

Output
The student's name is: Geeky

4. internal Modifier

Access is limited to only the current Assembly, that is any class or type declared as internal is accessible anywhere inside the same namespace. It is the default access modifier in C#. It is useful when you want to restrict access to code that should only be used within the same project or library.

Example:

C#
// Inside the file Geeks.cs
using System;

// Declare class Complex as internal
internal class Complex 
{
	int real;
	int img;

	public void setData(int r, int i)
	{
		real = r;
		img = i;
	}

	public void displayData()
	{
		Console.WriteLine("Real = {0}", real);
		Console.WriteLine("Imaginary = {0}", img);
	}
}

class Geeks 
{
	static void Main(string[] args)
	{
		// Instantiate the class Complex
		// in separate class but within 
		// the same assembly
		Complex c = new Complex();

		// Accessible in class Program
		c.setData(2, 1);
		c.displayData();
	}
}

Output
Real = 2
Imaginary = 1

5. protected internal

protected internal access modifier combines the features of protected and internal. It allows members to be accessed within the same assembly as well as in derived classes, regardless of whether they are in the same assembly or not.

Example: In the code given below, the Parent class which we create in the same assembly and we create another class named as GFG we access it In GFG from the Parent class. The member value is declared as protected internal therefore it is accessible throughout the class Parent and also in any other class in the same assembly like ABC. It is also accessible inside another class derived from Parent, namely Child which is inside another assembly.

Program 1: Parent.cs

C#
// Inside file Parent.cs
using System;

public class Parent
{
    // Declaring protected internal
    protected internal int value;
}

class ABC
{
    // Trying to access 
    // value in another class
    public void testAccess()
    {
        // Member value is Accessible
        Parent obj1 = new Parent();
        obj1.value = 12;
    }
}

Note: This program is in the same folder and the member value of Parent is protected internal and we can access it in the derived class with Parent class's instance.

Program 2: GFG.cs

C#
// Inside the file GFG.cs 
using System;

namespace GFG {

class Child : Parent {

	
	public static void Main(String[] args)
	{
		// Accessing value in another assembly
		Child obj2 = new Child();

		// Member value is Accessible
		obj2.value = 9;
		Console.WriteLine("Value = " + obj2.value);
	}
}
}

Output:

Value = 9

6. protected private Modifier

protected private access is only granted to the containing class. Any other class inside the current or another assembly is not granted access to these members. This modifier is valid in C# version 7.2 and later.

Example:

C#
// illustration of private protected 
// Accessibility Level
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()
	{
		// access value
		// Inside a derived class

		Console.WriteLine("Value = " + value);
		// value is accessible
	}
}


class Program 
 {	
	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());
	}
  }
}

Output:

Value = 4

Important Points

  • Namespaces doesn’t allow the access modifiers as they have no access restrictions.
  • The user is allowed to use only one accessibility at a time except the private protected and protected internal.
  • The default accessibility for the top-level types(that are not nested in other types, can only have public or internal accessibility) is internal.
  • If no access modifier is specified for a member declaration, then the default accessibility is used based on the context.

Next Article

Similar Reads