Encapsulation in C#

Encapsulation


Encapsulation in C#


Encapsulation – Consider it to be a Capsule hiding or enclosing something

Encapsulation is a process of binding the data members (Fields, Properties) and member functions (Methods or Function) into a single unit.


We can consider a class as real-time example for encapsulation because it will combine various types of data members and member functions into a single unit.


Since Encapsulation is also kind of capsule, it prevents outside world from accessing anything inside the capsule(Basically data inside this class will not be let accessed outside the class and its protected)


From the above point its very clear Encapsulation is also a Data Hiding, since Data inside the class is hidden from outside world in a capsule.


Encapsulation is achieved in C# by marking all the variables as Private and using Properties of C# to set the values and get the values of variables


In the below example, class "Encapsulation" is encapsulated as we are using private access modifier to protect the variable from being accessed from outside the class and we are making use of properties to set the value and get the value of variables.


using System;

using System.Collections.Generic;

using System.Text;

 

namespace Encapsulate

{

    public class Encapsulation

    {

        private int num1; // Private Access modifier field, cannot be accessed outside class

        private int num2; // Private Access modifier field, cannot be accessed outside class

 

        public int Num1 //Properties to access private field outside the class

        {

            set

            {

                num1 = value;

            }

            get

            {

                return num1;

            }

        }

 

        public int Num2 //Properties to access private field outside the class

        {

            set

            {

                num2 = value;

            }

            get

            {

                return num2;

            }

        }

 

        public void Add(int no1, int no2)      // Member Function

        {

            Console.WriteLine(no1+no2);

        }

    }

 

    public class Program

    {

        public static void Main()

        {

            Encapsulation obj = new Encapsulation();

            obj.Num1 = 10;

            obj.Num2 = 20;

            obj.Add(obj.Num1,obj.Num2);

        }

    }

}


0 comments: