Encapsulation in C#

What is Encapsulation?

Encapsulation is the process of hiding the irrelevant information and showing only the relevant information of a specific object to a user.

Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Array
{
    class Program
    {
        string name;

        public string Name   //Encapsulate the name member
        {
            get { return name; }
            set { name = value; }
        }
        int roll;

        public int Roll   //Encapsulate the roll member
        {
            get { return roll; }
            set { roll = value; }
        }
        static void Main(string[] args)
        {
            Program p = new Program();
            p.name = "Chandan";   //call set accessor of the property name
            p.roll = 1;   //call set accessor of the property roll

            //call get accessor of the property name
            Console.WriteLine("Name: " + p.Name);
            //call get accessor of the property roll
            Console.WriteLine("Roll: " + p.Roll);
            Console.ReadLine();
        }
    }
}

Output

Name: Chandan
Roll: 1


Write a comment


Name Email Message