11.2. Encapsulation

Encapsulation is defined as bundling data and related operations into a single unit. This is different from procedural approach of programming, where data and functionalities tend to separate. When bundling data with methods in the same class, encapsulation also shields the data from being accessed by the code outside the class.

In C#, encapsulation is achieved by granting no direct access to the data: By declaring the fields/variables of the class as private. To access and modify the private fields, C# uses properties, which are special public methods in the class to set and get the values of private fields.

There are several ways to implement encapsulation in C#:

  • Using properties

  • Using methods

11.2.1. Using Properties

Properties are a special type of class member that provide a way to read and write the value of a private field. They allow you to control access to the field while still providing a simple and convenient way to access its value.

 1namespace IntroCSCS {
 2    public class BankAccount
 3    {
 4        private decimal balance;
 5
 6        public decimal Balance              // Balance property; a special method with
 7        {                                   // getter and setter
 8            get { return balance; }
 9            set { balance = value; }
10        }
11    }
12
13    class Program{
14        // Can access balance through the Balance property
15        BankAccount account = new BankAccount();
16        account.Balance = 100;
17        Console.WriteLine(account.Balance);
18    }

11.2.2. Using methods

You can implement encapsulation by using methods to access and modify the values of private fields. This allows you to control access to the fields and enforce any necessary business logic or validation.

 1namespace IntroCSCS {
 2    public class BankAccount
 3    {
 4        private decimal balance;                        // private field
 5
 6        public BankAccount(decimal initialBalance)      // constructor; set default value
 7        {
 8            balance = initialBalance;
 9        }
10
11        public decimal GetBalance()                     // using method to implement encapsulation.
12        {
13            return balance;
14        }
15
16        public void Deposit(decimal amount)
17        {
18            balance += amount;
19        }
20
21        public void Withdraw(decimal amount)
22        {
23            balance -= amount;
24        }
25    }
26
27    class Program {
28        static void Main(string[] args)
29        {
30            BankAccount myAccount = new BankAccount(1000);
31
32            myAccount.Deposit(500);
33            Console.WriteLine("Balance: " + myAccount.GetBalance());
34                                                                // output: balance: 1500
35            myAccount.Withdraw(2000);
36            Console.WriteLine("Balance: " + myAccount.GetBalance());
37        }                                                       // Balance: -500
38    }
39}

Let us take a look at this class:

  • Security: You interact with the BankAccount object through its public methods, never directly accessing the balance field.

  • The ``BankAccount`` class: The BankAccount class encapsulates data (the balance field) and related operations (the Deposit and Withdraw methods).

  • The balance field: The balance field is marked as private, meaning it can only be accessed within the BankAccount class. This ensures that the balance can only be modified through the Deposit and Withdraw methods, which can enforce any necessary business logic or validation.

  • The GetBalance method: The GetBalance method, on the other hand, is marked as public, meaning it can be called from outside the BankAccount class. This allows other code to retrieve the balance without being able to modify it directly.

Take a look at another example. In the program below, the class Student is encapsulated as the variables are declared as private. To access these private variables we are using the Name and Age accessors which contain the get and set method to retrieve and set the values of private fields. Accessors are defined as public so that they can access in other class.

 1namespace IntroCSCS
 2{
 3    public class Student
 4    {
 5        private String studentName;     // private variables declared
 6        private int studentAge;         // these can only be accessed by public getter/setter
 7
 8        public String Name              // Property; getter/setter accessors
 9        {
10            get { return studentName; }
11            set { studentName = value; }
12        }
13
14        public int Age                  // getter/setter accessors to access Age
15        {
16            get { return studentAge; }
17            set { studentAge = value; }
18        }
19    }
20
21
22    class Program
23    {
24        static void Main(string[] args)
25        {
26
27            Student obj = new Student();
28            obj.Name = "TY Chen";           // set field value
29            obj.Age = 35;                   // set field value
30
31            Console.WriteLine(" Name : " + obj.Name);   // output: Name : TY Chen
32            Console.WriteLine(" Age : " + obj.Age);     // output: Age : 35
33        }
34    }
35}