The Wayback Machine - https://web.archive.org/web/20241008132906/https://www.geeksforgeeks.org/access-modifiers-in-c-sharp/
Open In App

Access Modifiers in C#

Last Updated : 20 Sep, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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:

The Accessibility table of these modifiers is given below:

 

  public protected internal protected internal private private protected
Entire program Yes No No No No No
Containing class Yes Yes Yes Yes Yes Yes
Current assembly Yes No Yes Yes No No
Derived types Yes Yes No Yes No No
Derived types within current assembly Yes Yes Yes Yes No Yes

 

public Accessibility Level

Access is granted to the entire program. This 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.
Syntax:
 

public TypeName

Example: Here, we declare a class Student which consists of two class members rollNo and name which are public. These members can access from anywhere throughout the code in the current and another assembly in the program. The methods getRollNo and getName are also declared as public.
 

csharp




// C# Program to show the use of
// public Access Modifier
using System;
 
namespace publicAccessModifier {
 
class Student {
 
    // Declaring members rollNo
    // and name as public
    public int rollNo;
    public string name;
 
    // Constructor
    public Student(int r, string n)
    {
        rollNo = r;
        name = n;
    }
 
    // methods getRollNo and getName
    // also declared as public
    public int getRollNo()
    {
        return rollNo;
    }
    public string getName()
    {
        return name;
    }
}
 
class Program {
   
    // Main Method
    static void Main(string[] args)
    {
        // Creating object of the class Student
        Student S = new Student(1, "Astrid");
 
        // Displaying details directly
        // using the class members
        // accessible through another method
        Console.WriteLine("Roll number: {0}", S.rollNo);
        Console.WriteLine("Name: {0}", S.name);
 
        Console.WriteLine();
 
        // Displaying details using
        // member method also public
        Console.WriteLine("Roll number: {0}", S.getRollNo());
        Console.WriteLine("Name: {0}", S.getName());
    }
}
}


Output: 

Roll number: 1
Name: Astrid

Roll number: 1
Name: Astrid

 

protected Accessibility Level

Access is limited to the class that contains the member and derived types of this class. It means a class which is the subclass of the containing class anywhere in the program can access the protected members.
Syntax: 
 

protected TypeName

Example: In the code given below, the class Y inherits from X, therefore, any protected members of X can be accessed from Y but the values cannot be modified.
 

csharp




// C# Program to show the use of
// protected Access Modifier
using System;
 
namespace protectedAccessModifier {
 
class X {
 
    // Member x declared
    // as protected
    protected int x;
 
    public X()
    {
        x = 10;
    }
}
 
// class Y inherits the
// class X
class Y : X {
 
    // Members of Y can access 'x'
    public int getX()
    {
        return x;
    }
}
 
class Program {
 
    static void Main(string[] args)
    {
        X obj1 = new X();
        Y obj2 = new Y();
 
        // Displaying the value of x
        Console.WriteLine("Value of x is : {0}", obj2.getX());
    }
}
}


Output: 

Value of x is : 10

 

internal Accessibility Level

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#.
Syntax:
 

internal TypeName

Example: In the code given below, The class Complex is a part of internalAccessModifier namespace and is accessible throughout it.
 

csharp




// C# Program to show use of
// internal access modifier
// Inside the file Program.cs
using System;
 
namespace internalAccessModifier {
 
// 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);
    }
}
 
// Driver Class
class Program {
 
    // Main Method
    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

 

Note: In the same code if you add another file, the class Complex will not be accessible in that namespace and compiler gives an error.
 

csharp




// C# program inside file xyz.cs
// separate nampespace named xyz
using System;
 
namespace xyz {
 
class text {
 
    // Will give an error during compilation
    Complex c1 = new Complex();
    c1.setData(2, 3);
}
}


Output: 

error CS1519

 

protected internal Accessibility Level

Access is limited to the current assembly or the derived types of the containing class. It means access is granted to any class which is derived from the containing class within or outside the current Assembly.
Syntax:
 

protected internal TypeName

Example: In the code given below, 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.
 

csharp




// Inside file parent.cs
using System;
 
public class Parent {
 
    // Declaring member as 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;
    }
}


csharp




// Inside file GFg.cs
using System;
 
namespace GFG {
 
class Child : Parent {
 
    // Main Method
    public static void Main(String[] args)
    {
        // Accessing value in another assembly
        Child obj3 = new Child();
 
        // Member value is Accessible
        obj3.value = 9;
        Console.WriteLine("Value = " + obj3.value);
    }
}
}


Output: 

Value = 9

 

private Accessibility Level

Access is only granted to the containing class. Any other class inside the current or another assembly is not granted access to these members.
Syntax:
 

private TypeName

Example: In this code we declare the member value of class Parent as private therefore its access is restricted to only the containing class. We try to access value inside of a derived class named Child but the compiler throws an error {error CS0122: ‘PrivateAccessModifier.Parent.value’ is inaccessible due to its protection level}. Similarly, inside main {which is a method in another class}. obj.value will throw the above error. So we can use public member methods that can set or get values of private members.
 

csharp




// C# Program to show use of
// the private access modifier
using System;
 
namespace PrivateAccessModifier {
 
class Parent {
 
    // Member is declared as private
    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
    }
}
 
// Driver Class
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

 

private protected Accessibility Level

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.
Syntax:
 

private protected TypeName

Example: This code is same as the code above but since the Access modifier for member value is ‘private protected’ it is now accessible inside the derived class or Parent namely Child. Any derived class that maybe present in another assembly will not be able to access these private protected members.
 

csharp




// C# Program to show use of
// the 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()
    {
        // Trying to access value
        // Inside a derived class
 
        Console.WriteLine("Value = " + value);
        // value is accessible
    }
}
 
// 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());
    }
}
}


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.

 



Similar Reads

How to get Synchronize access to the Array in C#
Array.SyncRoot Property is used to get an object that can be used to synchronize access to the Array. An array is a group of like-typed variables that are referred to by a common name. Array class comes under the System namespace. Important Points: Synchronization of an object is done so that only one thread can manipulate the data in the array. A
3 min read
How to get Synchronize access to the Queue in C#
Queue.SyncRoot Property is used to get an object which can be used to synchronize access to the Queue. Queue represents a first-in, first out collection of object. It is used when you need first-in, first-out access of items. When you add an item in the list, it is called enqueue, and when you remove an item, it is called dequeue. This class comes
2 min read
C# | How to get Synchronize access to the ArrayList
ArrayList.SyncRoot Property is used to get an object which can be used to synchronize access to the ArrayList. ArrayList represents an ordered collection of an object that can be indexed individually. It is basically an alternative to an array. It also allows dynamic memory allocation, adding, searching and sorting items in the list. Important Poin
2 min read
How to get Synchronize access to the Stack in C#
Stack.SyncRoot Property is used to get an object which can be used to synchronize access to the Stack. Stack represents last-in, first out collection of object. It is used when you need last-in, first-out access to items. When you add an item in the list, it is called pushing the item and when you remove it, it is called popping the item. This clas
3 min read
How to get Synchronize access to the ListDictionary in C#
ListDictionary.SyncRoot Property is used to get an object which can be used to synchronize access to the ListDictionary. ListDictionary is a specialized collection. It comes under the System.Collections.Specialized namespace. This type represents a non-generic dictionary type. It is implemented with a linked list. Syntax: public virtual object Sync
3 min read
How to get Synchronize access to the StringCollection in C#
StringCollection.SyncRoot Property is used to get an object which can be used to synchronize access to the StringCollection. This class library that represents a collection of strings. StringCollection class is defined in the System.Collections.Specialized namespace. Syntax: public virtual object SyncRoot { get; } Property Value: An object which ca
2 min read
How to get Synchronize access to the HybridDictionary in C#
HybridDictionary.SyncRoot Property is used to get an object which can be used to synchronize access to the HybridDictionary. It implements a linked list and hash table data structure. It implements IDictionary by using a ListDictionary when the collection is small, and a Hashtable when the collection is large. Syntax: public virtual object SyncRoot
3 min read
How to get Synchronize access to the StringDictionary in C#
StringDictionary.SyncRoot Property is used to get an object which can be used to synchronize access to the StringDictionary. It only allows string keys and string values. It suffers from performance problems. It implements a hash table with the key and the value strongly typed to be strings rather than objects. Syntax: public virtual object SyncRoo
3 min read
How to access structure elements using Pointers in C#
Unlike C/C++, Structures in C# can have members that are methods, fields, indexers, operator methods, properties or events. The members can have access specifiers as public, private, and internal. Pointers are variables that store the addresses of the same type of variable i.e. an int pointer can store an address of an integer, a char pointer can s
3 min read
C# Program to View the Access Date and Time of a File
Given a file, our task is to view the date and time of access to a file. So to do this we use the following properties of the FileSystemInfo class: 1. CreationTime: This property is used to get the time in which the file is created. Syntax: file.CreationTime Where the file is the path of the file and it will return DateTime. A DateTime structure is
2 min read
C# Tutorial
In this C# (C Sharp) tutorial, whether you’re beginner or have experience with other programming languages, our free C# tutorials covers the basic and advanced concepts of C# including fundamentals of C#, including syntax, data types, control structures, classes, and objects. You will also dive into more advanced topics like exception handling, and
8 min read
ASP.NET Interview Questions and Answer
ASP.NET is a powerful framework for building dynamic web applications, known for its scalability, performance, and integration with the .NET ecosystem, developed by Microsoft that allows developers to build dynamic web applications, websites, and services. It is part of the larger .NET framework and provides a comprehensive programming model for cr
15+ min read
C# Interview Questions and Answers
C# is the most popular general-purpose programming language and was developed by Microsoft in 2000, renowned for its robustness, flexibility, and extensive application range. It is simple and has an object-oriented programming concept that can be used for creating different types of applications. Here, we will provide 50+ C# Interview Questions and
15+ min read
Program to calculate Electricity Bill
Given an integer U denoting the amount of KWh units of electricity consumed, the task is to calculate the electricity bill with the help of the below charges: 1 to 100 units - [Tex]Rs. 10/unit[/Tex]100 to 200 units - [Tex]Rs. 15/unit[/Tex]200 to 300 units - [Tex]Rs. 20/unit[/Tex]above 300 units - [Tex]Rs. 25/unit[/Tex] Examples: Input: U = 250 Outp
9 min read
HashSet in C# with Examples
In C#, HashSet is an unordered collection of unique elements. This collection is introduced in .NET 3.5. It supports the implementation of sets and uses the hash table for storage. This collection is of the generic type collection and it is defined under System.Collections.Generic namespace. It is generally used when we want to prevent duplicate el
6 min read
C# Dictionary with examples
In C#, Dictionary is a generic collection which is generally used to store key/value pairs. The working of Dictionary is quite similar to the non-generic hashtable. The advantage of Dictionary is, it is generic type. Dictionary is defined under System.Collections.Generic namespace. It is dynamic in nature means the size of the dictionary is growing
5 min read
Difference between Abstract Class and Interface in C#
An abstract class is a way to achieve abstraction in C#. To declare an abstract class, we use the abstract keyword. An Abstract class is never intended to be instantiated directly. This class must contain at least one abstract method, which is marked by the keyword or modifier abstract in the class definition. The Abstract classes are typically use
4 min read
C# | Arrays of Strings
An array is a collection of the same type variable. Whereas a string is a sequence of Unicode characters or array of characters. Therefore arrays of strings is an array of arrays of characters. Here, string array and arrays of strings both are same term. For Example, if you want to store the name of students of a class then you can use the arrays o
4 min read
Collections in C#
.math-table { border-collapse: collapse; width: 100%; } .math-table td { border: 1px solid #5fb962; text-align: left !important; padding: 8px; } .math-table th { border: 1px solid #5fb962; padding: 8px; } .math-table tr>th{ background-color: #c6ebd9; vertical-align: middle; } .math-table tr:nth-child(odd) { background-color: #ffffff; } Collectio
5 min read
Introduction to .NET Framework
The .NET Framework is a software development framework developed by Microsoft that provides a runtime environment and a set of libraries and tools for building and running applications on Windows operating systems. The framework includes a variety of programming languages, such as C#, F#, and Visual Basic, and supports a range of application types,
7 min read
Common Language Runtime (CLR) in C#
The Common Language Runtime (CLR) is a component of the Microsoft .NET Framework that manages the execution of .NET applications. It is responsible for loading and executing the code written in various .NET programming languages, including C#, VB.NET, F#, and others. When a C# program is compiled, the resulting executable code is in an intermediate
6 min read
C# | List Class
List<T> class represents the list of objects which can be accessed by index. It comes under the System.Collections.Generic namespace. List class can be used to create a collection of different types like integers, strings etc. List<T> class also provides the methods to search, sort, and manipulate lists. Characteristics: It is different
6 min read
C# | Encapsulation
Encapsulation is defined as the wrapping up of data and information under a single unit. It is the mechanism that binds together the data and the functions that manipulate them. In a different way, encapsulation is a protective shield that prevents the data from being accessed by the code outside this shield. Technically in encapsulation, the varia
5 min read
C# | Method Overriding
Method Overriding in C# is similar to the virtual function in C++. Method Overriding is a technique that allows the invoking of functions from another class (base class) in the derived class. Creating a method in the derived class with the same signature as a method in the base class is called as method overriding. In simple words, Overriding is a
8 min read
C# | Delegates
A delegate is an object which refers to a method or you can say it is a reference type variable that can hold a reference to the methods. Delegates in C# are similar to the function pointer in C/C++. It provides a way which tells which method is to be called when an event is triggered. For example, if you click on a Button on a form (Windows Form a
6 min read
C# | Inheritance
Introduction: Inheritance is a fundamental concept in object-oriented programming that allows us to define a new class based on an existing class. The new class inherits the properties and methods of the existing class and can also add new properties and methods of its own. Inheritance promotes code reuse, simplifies code maintenance, and improves
7 min read
C# | Generics - Introduction
Generic is a class which allows the user to define classes and methods with the placeholder. Generics were added to version 2.0 of the C# language. The basic idea behind using Generic is to allow type (Integer, String, â€Ķ etc and user-defined types) to be a parameter to methods, classes, and interfaces. A primary limitation of collections is the abs
6 min read
C# | Substring() Method
In C#, Substring() is a string method. It is used to retrieve a substring from the current instance of the string. This method can be overloaded by passing the different number of parameters to it as follows: String.Substring(Int32) Method String.Substring(Int32, Int32) Method String.Substring Method (startIndex) This method is used to retrieves a
3 min read
C# | Arrays
An array is a group of like-typed variables that are referred to by a common name. And each data item is called an element of the array. The data types of the elements may be any valid data type like char, int, float, etc. and the elements are stored in a contiguous location. Length of the array specifies the number of elements present in the array
13 min read
C# | Data Types
Data types specify the type of data that a valid C# variable can hold. C# is a strongly typed programming language because in C#, each type of data (such as integer, character, float, and so forth) is predefined as part of the programming language and all constants or variables defined for a given program must be described with one of the data type
7 min read
Article Tags :