Encapsulation in C# using an example
- By Gurunatha Dogi in C#
- May 3rd, 2013
- 124807
- 32
Encapsulation is way to hide data, properties and methods from outside the world or
outside of the class scope and exposing only necessary thing.Encapsulation complements Abstraction. Abstraction display only important features of a class and Encapsulation hides unwanted data or private data from outside of a class.It hides the information within the object and prevents from accidental corruption.
How we can achieve Encapsulation
We can achieve Encapsulation by using "private" access modifier as shown in below snippet of code.
class Employee{ private void AccountInformation(){ Console.WriteLine("Displaying Account Details"); } }
Why to use Encapsulation
Encapsulation means protecting important data inside the class which we do not
want to be exposed outside of the class.
Lets consider example of a Television(TV).
If you have seen important TV machine, TV connections and TV color tube is hidden inside the TV case which is not been exposed for viewers like us and exposed only neccessary things of a TV like TV Channel keys, TV volume keys, ON/OFF switch, Cable Switch and TV remote control for viewers to use it.This means TV machine, TV connections and TV color tube is an unwanted data and not needed for viewers to see is been hidden from outside the world.
So encapsulation means hiding the important features of a class which is not been needed to be exposed outside of a class and exposing only necessary things of a class.
Here hidden part of a class acts like Encapsulation and exposed part of a class acts like Abstraction.
For more information on Abstraction check out this article Abstraction in Csharp with an example.
Example of Encapsulation using Csharp
class clsTelevision{ private void TVmachine(){ Console.WriteLine("Machine of a Television"); } private void TVcolortube(){ Console.WriteLine("Color Tube of a Television"); } public void TVKeys(){ Console.WriteLine("Keys of a Television"); } public void TVRemote(){ Console.WriteLine("Remote of a Television"); } public void TVScreen(){ Console.WriteLine("Wide Screen of a Television"); } }
So as you can see from our above code that we have hidden core part of a television methods by using "private" access modifier and exposed only necessary methods for a viewers to use it using "public" access modifier.
So before implementing encapsulation or abstaction think in terms of real world scenario as needed for your application or list down things which you want hide or display in your applications.
For any doubts kindly let me know through your comments.
Gurunatha Dogi
Gurunatha Dogi is a software engineer by profession and founder of Onlinebuff.com, Onlinebuff is a tech blog which covers topics on .NET Fundamentals, Csharp, Asp.Net, PHP, MYSQL, SQL Server and lots more..... read more