Encapsulation in C#

Definition

Encapsulation is implemented in C# by using the private access specifier. In this section, you learn to create an application, name Employee to encapsulate data using accessors and mutators. Accessors and mutators are methods that are used to get and set the values of a variable.

Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Employee
{
    public class EmployeeDetail
    {
    private string Name; 
    //Accessor
    public string get()
    {
    return Name;
    }
    //Mutators
    pubilc string set(string name)
    {
    Name=name;
    }
    }
public class MainClass
{
    public static void Main(string[] args)
    { 
    EmployeeDetail detail=new EmployeeDetail();
    detail.set("Vaidehi");
    Console.WriteLine("The Employee Name is :" + detail.get());
    Console.ReadLine();
    }
}
}

We have defined two methods set and get. The set method, mutator, sets the value of the Name variable. The get method, accessor, displays the value of the Name variable on the screen.

Output

The Employee Name is :Vaidehi

Press ENTER to quit....


Write a comment


Name Email Message