Introduction
In the Object Oriented Programming , we always heard a term encapsulation. Encapsulation or data hiding is the very important topic in OOP. encapsulation means to wrapping up the data and methods into single unit. Now the question is that how can we achieved the encapsulation in C#.
C# provides accessor methods (get and set methods) which are used to achieve the encapsulation in the C#.
Let's look the class that will represent the user's login name, password and so on.
public class LogInToken { public string Name; public string Password; }
The Name and Password values are completely accessible by anyone using this class file. Following the rules of encapsulation, we can hide the data by making the access modifier private:
public class LogInToken { private string Name; private string Password; }
nOW, we need to provide a public exposed method that will allow access to the Name and Password. These are called accessor methods, or setters and getters.
There are two ways of encapsulating or hiding the data.
1. CREATING METHODS TO HIDE DATA
See the GetName() and GetPassword() methods which are used to access these private members.
public string GetName() { return Name; } public string GetPassword() { return Password; }
For setting the values of name and password , we will use the setters like :
public void SetName (string newName) { Name = NewName; } public void SetPassword (string newPassword) { if (Name == "mm") Password = newPassword; else // throw exception that password is invalid }
2. USING PROPERTIES TO HIDE DATA
The second way to control access to data within a class file is by using properties. Instead of creating methods that start with Get or Set, you simply make the pseudo-method “look” like the data.
public string Name { get { return name; } set { name = value; // C# uses the implicit parameter "value" } } public string Password { get { return password; } set { if (name == "mm") password = value; else // throw an exception here for invalid password } }
SUMMARY
Which method you use is a matter of personal preference.By creating GetPassword and SetPassword methods as in the earlier examples, you are asking that the user of your class become familiar with all the methods needed to access data. When you use properties, the user simply needs to know the property names and can treat them as data instead of methods.
Thanks Gaurav Sharma
|
| Author: Puja Sharma 16 Oct 2008 | Member Level: Gold Points : 2 |
Hi Gaurav
This is a very nice article. It cleared my idea of encapsulation. Thanks for the article.
Varun Sharma
|