Access Modifiers in C#

access modifiers

What are access modifiers?

Access modifiers set the access level to classes, structs, and their members.

C# supports 5 types of access modifiers.

  1. Public
  2. Private
  3. Internal
  4. Protected
  5. Internal Protected

Public:

This access modifier will make your class and/or its members available everywhere. You can access them from other classes, other assemblies (assembly means project here), etc.

You have a class First and it has one method called SomeMethod as below.

public class First
{
  public void SomeMethod()
       {
       }
}

Since you have made this class and method public, they are accessible from anywhere in the code, within and outside of an assembly.

class Second
{
       public void Caller()
       {
              First first = new First();
              first.SomeMethod();
       }    
}

Classes and structs and their members support this access modifier. The interface support only public access modifier. If you are new to the interface, I tried to explain it here.

Private:

This access modifier is the most strict one. You can use members declared as private only within the class. In the above example, if you set SomeMethod as private, you will get this error while accessing it outside.

'First.SomeMethod()' is inaccessible due to its protection level

Only members of the class and struct support this access modifier, not classes or structs. This is the default one for all the members of the class like fields, properties, methods, events, etc.

Internal:

This access modifier makes classes or their members available in other classes within the assembly. If you try to access them from outside assembly you will get a similar error. Classes and structs and their members support this access modifier. This is the default one for classes and structs.

Protected:

This access modifier makes members of a class available in the same class or its subclasses.

public class First
{
      protected void SomeMethod()
      {
      }
}

class Second : First
{
      public void Caller()
      {
            SomeMethod();
      }        
}

Internal Protected:

This is a combination and internal and protected which means they are accessible in

  1. Same class
  2. Subclass
  3. Within assembly.

Only members of the class and struct support this access modifier, not classes or structs.

I hope this article was helpful.

CategoriesC#

Leave a Reply

Your email address will not be published. Required fields are marked *

Coding Crest Back To The Top