Encapsulation or information hiding is the process of hiding  the sensitive data of an object from a user and only providing him/her with what  is necessary. When we define a class, we often have states, which are the data  members that store the values about the object. Some of these data members are  used by the class itself to support the functionality of methods and sometimes, act as temporary variables. This kind of data members is called utility members because they are only used to support the methods and not as a visible data of the class. Not all of the data members or methods is needed by the user or the one who will use the class. Allowing these type of data members to be accessed outside of the class is dangerous as the user can modify the behavior and the results of the methods. Consider a simple program below:

using System;
 
namespace EncapsulationDemo
{
    public class Test
    {
        public int five = 5;
 
        public int AddFive(int number)
        {
            number += five;
            return number;
        }
    }
 
    public class Program
    {
        public static void Main()
        {
            Test x = new Test();
 
            x.five = 10;
            Console.WriteLine(x.AddFive(100));
        }
    }
}

Example 1 – Not Using Encapsulation

110

The method inside the Test class is named AddFive which has a simple purpose of adding the value 5 to any number. Inside the Main()method, we created an instance of the Test class and modified the value of the data member  five and assigned it a new value of 10. Now, the functionality of method AddFive() has been modified as well and you will now get different results. This is why encapsulation is important.

The things we’ve done in the last chapters which are making the data members public and allowing the user to access them outside of the class is a wrong practice. We only did that for demonstration purposes. Data members should always be private. Starting now, we will do the right way of creating a class by introducing properties in the next lesson.