Access modifiers and it’s Importance

Access modifiers is one of the important parts of object-oriented programming which is often overlooked. This is used to define and implement some fundamental concepts in object-oriented programming. Access modifiers are keywords used to define the accessibility or scope of type or members. Different programming languages have different access modifiers, but we will look at the access modifiers in c#.

What is the importance of Access Modifiers?

We need access modifiers to restrict the scope of a type or member, this is also used to implement encapsulation and functionality hiding in the code. A good example is, we could use the these keywords to define which methods or types needs to be accessed outside the assembly or which types needs to be accessed inside the same class.

Lets imagine a scenario where we want to develop a component that formats the data in a certain way and inserts the data in the database. The method that we plan to expose only takes the information that we need to insert into the database, we plan to validate the data and format it in a certain way before inserting. In this scenario we don’t have to expose all the utility methods like the ones that are used to format data, validate data or methods used to create a connection and handle transactions. Access modifiers is used to accomplish this.

C# provides five access modifiers and they are given below.

Access ModifierContaining ClassDerived ClassContaining AssemblyOutside Containing Assembly
privateYesNoNoNo
publicYesYesYesYes
internalYesNoYesNo
protectedYesYesNoNo
protected internalYesYesYesNo

Note: In case of derived classes, base classes should be at least as accessible as the derived classes else compiler will throw error.
TypesDefault Accessibility of TypesDefault Accessibility of members in typeAllowed Accessibility of members in type
enuminternalpublicNone
classinternalprivatepublic
private
internal
protected
protected internal
interfaceinternalpublicNone
structinternalprivatepublic
private
internal

 

It is the developer’s responsibility to decide and define the accessibility of each type or member. These are just pointers to be kept in mind when defining the accessibility. Please keep these pointers in mind when programming and have fun programming.

Some useful references on C# Access Modifiers:

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/accessibility-levels

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/access-modifiers

Site Footer