C# Tutorial - Encapsulation in C#
In Object Oriented Programming, Encapsulation is one of the main key feature and main purpose of it is to prevent access to implementation details. In previous tutorial, we have discussed access specifiers, which are used for controlling access to fields and methods in class. So access specifiers are used for achieving encapsulation. Encapsulation allows to encapsulate data and to protect it from being modified accidentally or deliberately. Encapsulation prevents data from accidental manipulation or corruption. To achieve encapsulation, instead of declaring them public we declare them as private. These private fields are then can be modified using two ways.
- By using Accessor & Mutator
- By using Named Properties
By using Acessor & Mutator
class Account { private int accountnumber;
//Accessor
public int GetAccountNumber()
{
return accountnumber;
}
//Mutator
public void SetAccountNumber(int value)
{
accountnumber = value;
}
}
class Program {
public static void Main()
{
Account a = new Account();
a.SetAccountNumber = 123456;
Console.WriteLine(a.GetAccountNumber);
}
}
In above example you can see that we are accessing SetAccountNumber method also called Accessor in order to set value of field account number in Account class and we are using GetAccountNumber method also called Mutator to acquire the value of account number field in Account class.
By using Named Properties
class Account { private int accountnumber;
//Named Property
public int AccountNumber()
{
get { return accountnumber; }
set { accountnumber = value; }
}
}
class Program {
public static void Main()
{
Account a = new Account();
a.AccountNumber = 123456;
Console.WriteLine(a.AccountNumber);
}
}
In this example, we have used properties in order to access private fields with get and set methods for
accessing private field of class Account.
No comments:
Post a Comment