C# Access Modifiers

In C#, access modifiers are used to define the scope of a class member. Access modifiers determine which classes can access a particular member of a class.

There are four types of access modifiers in C#:

  • Public
  • Private
  • Protected
  • Internal

Public Access Modifier

The public access modifier makes a class member accessible from any code in the application. This means that any code in the same assembly or in another assembly can access the public member.

Example:

1public class MyClass 2{ 3 public int MyPublicField; 4 public void MyPublicMethod() 5 { 6 //method implementation 7 } 8}

Private Access Modifier

The private access modifier makes a class member accessible only within the same class. This means that other classes cannot access the private member.

Example:

1public class MyClass 2{ 3 private int MyPrivateField; 4 private void MyPrivateMethod() 5 { 6 //method implementation 7 } 8}

Protected Access Modifier

The protected access modifier makes a class member accessible within the same class or any derived class. This means that other classes cannot access the protected member, but any derived class can access the protected member.

Example:

1public class MyClass 2{ 3 protected int MyProtectedField; 4 protected void MyProtectedMethod() 5 { 6 //method implementation 7 } 8} 9 10public class MyDerivedClass : MyClass 11{ 12 public void SomeMethod() 13 { 14 MyProtectedField = 10; // access protected field of the base class 15 MyProtectedMethod(); // access protected method of the base class 16 } 17}

Internal Access Modifier

The internal access modifier makes a class member accessible within the same assembly. This means that other assemblies cannot access the internal member.

Example:

1public class MyClass 2{ 3 internal int MyInternalField; 4 internal void MyInternalMethod() 5 { 6 //method implementation 7 } 8}

Combining Access Modifiers

It is possible to combine access modifiers, for example, to make a member accessible within a specific class hierarchy or to restrict access to a certain method:

Example:

1public class MyClass 2{ 3 private protected int MyProtectedPrivateField; 4 public internal void MyPublicInternalMethod() 5 { 6 //method implementation 7 } 8}

In this example, the MyProtectedPrivateField can only be accessed by classes derived from MyClass, and the MyPublicInternalMethod can only be accessed within the same assembly or by derived classes.