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
using System;
namespace publicAccessModifier {
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 Program {
static void Main(string[] args)
{
Student S = new Student(1, "Astrid");
Console.WriteLine("Roll number: {0}", S.rollNo);
Console.WriteLine("Name: {0}", S.name);
Console.WriteLine();
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
using System;
namespace protectedAccessModifier {
class X {
protected int x;
public X()
{
x = 10;
}
}
class Y : X {
public int getX()
{
return x;
}
}
class Program {
static void Main(string[] args)
{
X obj1 = new X();
Y obj2 = new Y();
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
using System;
namespace internalAccessModifier {
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 Program {
static void Main(string[] args)
{
Complex c = new Complex();
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
using System;
namespace xyz {
class text {
Complex c1 = new Complex();
c1.setData(2, 3);
}
}
|
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
using System;
public class Parent {
protected internal int value;
}
class ABC {
public void testAccess()
{
Parent obj1 = new Parent();
obj1.value = 12;
}
}
|
csharp
using System;
namespace GFG {
class Child : Parent {
public static void Main(String[] args)
{
Child obj3 = new Child();
obj3.value = 9;
Console.WriteLine("Value = " + obj3.value);
}
}
}
|
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
using System;
namespace PrivateAccessModifier {
class Parent {
private int value;
public void setValue(int v)
{
value = v;
}
public int getValue()
{
return value;
}
}
class Child : Parent {
public void showValue()
{
}
}
class Program {
static void Main(string[] args)
{
Parent obj = new Parent();
obj.setValue(4);
Console.WriteLine("Value = " + obj.getValue());
}
}
}
|
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
using System;
namespace PrivateProtectedAccessModifier {
class Parent {
private protected int value;
public void setValue(int v)
{
value = v;
}
public int getValue()
{
return value;
}
}
class Child : Parent {
public void showValue()
{
Console.WriteLine("Value = " + value);
}
}
class Program {
static void Main(string[] args)
{
Parent obj = new Parent();
obj.setValue(4);
Console.WriteLine("Value = " + obj.getValue());
}
}
}
|
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
C# | Identifiers
In programming languages, identifiers are used for identification purposes. Or in other words, identifiers are the user-defined name of the program components. In C#, an identifier can be a class name, method name, variable name, or label. Example: public class GFG { static public void Main () { int
2 min read
TimeSpan.Add() Method in C#
This method is used to a get new TimeSpan object whose value is the sum of the specified TimeSpan object and this instance. Syntax public TimeSpan Add (TimeSpan t); Parameter: t: This parameter specifies the time interval to be added. Return Value: It returns a new TimeSpan object whose value is the
2 min read
C# - FileInfo Class Methods
In this article, we will explain the FileInfo class, its methods, properties, etc. The System.IO namespace is one of the most important namespaces we used while we are working with files in C#. FileInfo Class:It does not have static methods and it can only be used on instantiated objects. The class
3 min read
Anonymous Method in C#
An anonymous method is a method which doesnât contain any name which is introduced in C# 2.0. It is useful when the user wants to create an inline method and also wants to pass parameter in the anonymous method like other methods. An Anonymous method is defined using the delegate keyword and the use
3 min read
Iterators in C#
An iterator is a method in C# which is used in an array or in collections like the list, etc. to retrieve elements one by one. Or in other words, we can say that an iterator is used to perform an iteration over the collections. This feature is introduced in C# 2.0. It uses the yield return statement
3 min read
C# | StringDictionary Class
.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-chil
5 min read
Stack.Equals() Method in C#
Equals(Object) Method which is inherited from the Object class is used to check if a specified Stack class object is equal to another Stack class object or not. This method comes under the System.Collections namespace. Syntax: public virtual bool Equals (object obj); Here, obj is the object which is
2 min read
Stack.Count Property in C#
This method(comes under System.Collections namespace) is used to get the number of elements contained in the Stack. The capacity is the number of elements that the Stack can store and the count is the number of elements that are actually in the Stack. The capacity is always greater than or equal to
2 min read
Null-Coalescing Operator in C#
In C#, ?? operator is known as Null-coalescing operator. It will return the value of its left-hand operand if it is not null. If it is null, then it will evaluate the right-hand operand and returns its result. Or if the left-hand operand evaluates to non-null, then it does not evaluate its right-han
4 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 st
3 min read
Expression-Bodied Members in C#
Expression-bodied members provide a minimal and concise syntax to define properties and methods. It helps to eliminate boilerplate code and helps writing code that is more readable. The expression-bodied syntax can be used when a member's body consists only of one expression. It uses the =>(fat a
7 min read
byte Keyword in C#
Keywords are the words in a language that are used for some internal process or represent some predefined actions. byte is a keyword that is used to declare a variable which can store an unsigned value range from 0 to 255. It is an alias of System.Byte. byte keyword occupies 1 byte (8 bits) in the m
2 min read
char keyword in C#
Keywords are the words in a language that are used for some internal process or represent some predefined actions. char is a keyword that is used to declare a variable which store a character value from the range of +U0000 to U+FFFF. It is an alias of System.Char. Syntax: char variable_name = value;
2 min read
Range and Indices in C# 8.0
As we already know about the Range and Indices. We use them several times in our programs, they provide a short syntax to represent or access a single or a range of elements from the given sequence or collections. In this article, we will learn what's newly added in the range and indices in C# 8.0.
6 min read
Index Constructor in C#
Index(Int32, Boolean) constructor of Index Struct in C# 8.0 is used to initialize a new index with the specified index position and a value which shows whether the index starts from the start or the end of the collection or sequence. If the specified index created from the end, then the index value
3 min read
StringBuilder.ToString Method in C#
This method is used to converts the value of this instance to a String. A new String object is created and initialized to get the character sequence from this StringBuilder object and then String is returned by ToString(). Subsequent changes to this sequence contained by Object do not affect the con
2 min read
How to create an OrderedDictionary in C#
OrderedDictionary() constructor is used to initialize a new instance of the OrderedDictionary class which will be empty and will have the default initial capacity. OrderedDictionary Class represents a collection of key/value pairs that are accessible by the key or index. It is present in System.Coll
2 min read
LINQ | Set Operator | Intersect
In LINQ, Set operators are those operators in query expression which return a result set which is based on the existence or non-existence of the equivalent elements within the same or different collections or sequences or sets. The standard query operator contains the following set operators: Union
3 min read
C# | Dictionary Class
The Dictionary<TKey, TValue> Class in C# is a collection of Keys and Values. It is a generic collection class in the System.Collections.Generic namespace. The Dictionary <TKey, TValue> generic class provides a mapping from a set of keys to a set of values. Each addition to the dictionary
7 min read