Access Modifiers in C#

Access Modifiers / Access Specifiers are keywords used in object oriented programming to restrict access to classes or class members like methods and variables. It is a part of programming syntax to achieve the encapsulation of components. There are different kinds of Access Modifiers with different kind of behaviors. Access Modifiers in C# are

  • Public
  • Private
  • Internal
  • Protected
  • Protected Internal
  • Sealed

Public

It can be accessed from anywhere as object or for inheritance. In C# public is default for interfaces

Private

It is only accessible inside the same class. When an object of the class is created, private methods and variables won’t be accessible. In the case of inheritance, private properties and methods are inherited, but won’t be accessible. Nothing can be created as private direct under namespace. Which means a class direct under namespace cannot be given private modifier. Only nested class can be assigned as private. In C# private is default for class members.

Internal

This is just like public, but scope only inside the assembly. Outside the assembly, It won’t be available for inheritance as well as for object. In C#, internal is default for a class direct under namespace.

Protected

It is only available for inheritance, will not be accessible from object of the class. Which means, a protected member can be used only inside the child class not directly from parent class. Scope for inheritance is anywhere:- accessible from outside of the assembly also possible. A class direct under namespace cannot be created as protected.

Protected Internal

This is the union of Protected and Internal. It can be accessed from object only inside the assembly, but accessible for inheritance globally. As protected, no element direct under namespace can be created as protected internal.

Sealed

Sealed modifier is used to protect the class or class member from being inherited. A class with sealed modifier cannot be inherited, but it can inherit another class. But in case of class members, it can only be used to overridden members. Which means a new member cannot be create as sealed. So it protect class members fro multi level inheritance.

    class A
    {
        String name;
    }
    sealed class B : A
    {
        int Age; //this is possible B can inherit A
    }
    class C : B
    {
        DateTime DOB;   // This will return error on compile time, bcz, sealed class B cannot be inherited.
    }

Summary

Refer for more OOPS Concepts

2 thoughts on “Access Modifiers in C#

Leave a Reply