How can we implement Encapsulation in C#?



How can we implement Encapsulation in C#?

Encapsulation in C# using Accessors and Mutators:

Let us see an example to understand this concept. In the following example, we declare the balance variable as private in the Bank class, and hence it can not be accessed directly outside of the Bank class. In order to access this balance variable, we have exposed two public methods i.e. get balance and set the balance. The getBalance method (Accessors) is used to fetch the value stored in the balance variable whereas the set balance method (Mutator) is used to set the value in the balance variable.


namespace CsharpCode_EncapsulationDemo

{

    public class HDFCBank

    {

        //hiding class data by declaring the variable as private

        private double balance;

        //creating public setter and getter methods

        public double getBalance()

        {

            //add validation logic if needed

            return balance;

        }

        public void setBalance(double balance)

        {

            // add validation logic to check whether data is correct or not

            this.balance = balance;

        }

    }

    class HDFCBankUser

    {

        public static void Main()

        {

            HDFCBank hDFCBank = new HDFCBank();

            hDFCBank.setBalance(500);

            Console.WriteLine(hDFCBank.getBalance());

            Console.WriteLine("Press any key to exist.");

            Console.ReadKey();

        }

    }

}

0 Comment's

Comment Form