Monday, 26 October 2015

Encapsulation in C#

Encapsulation is one of the main concept of Object-Oriented Programming. You must have seen and had a capsule (medicine) in life as a gift from doctor when you get ill. Capsule mainly consist some powder substance in it  which is wrapped with a cover.

The same way when we cover up details of things ( data members and function ) into a single unit 
( such as class ) it is called encapsulation.




Definition : 

Encapsulation, refers to an ability to hide data and behavior that are not necessary to its user. Encapsulation enables a group of properties, methods and other members to be considered a single unit or object.

Using Encapsulation In C#


Encapsulation in c#  can be  achieved by following ways :

Using Access Modifiers :


Access modifiers basically defines the scope and visibility of a class member. It help to make the scope of some members limited to a particular point. For example if you dont want your mobile phone to be used by someone else you put a keypad lock on it so that no one else can you it. That make the phone as a private property to you.

C# supports the following access specifiers :

Public  : As the name specifies it it available to all, means the members marked public are available within and outside the class.

Private : It is available only within the class.

Protected : Members marked protected are available within the class and by derived class           instances. 

Internal :  internal keyword is an access modifier for types and type members. Internal types or members are accessible only within files in the same assembly

Protected Internal :  can be accessed from the current assembly or from types that are derived from the containing class.

By using properties


Properties in C# helps in protect a field in a class by reading and writing to it. We can use a property (which has a get and set part), or we can use a read only property (which has only a get part) or we can also use a write only property (which has only a set part). But in all cases we can achieve encapsulation

Example:

public class Account
{
   private string accountName = "current account";
   public string AccountName
 {
   get
     {return accountName;}
  set
  {
     accountName = value;
  }
 }
}





No comments:

Post a Comment