+92 332 4229 857 99ProjectIdeas@Gmail.com

Encapsulation (C#.net)



Encapsulation:
Encapsulation is the technique in which you hide the class members (variables) by declaring them to private so that they cannot be access out of the class except its public methods. It has the ability to change the implemented code dynamically.

Code


public class Employee
{
       private int id;

       // Getter/Setter of id
       public int Id
       {
            get { return id; }
            set { id = value; }
       }

       private string name;

      // Getter/Setter of name
       public string Name
       {
            get { return name; }
            set { name = value; }
       }

       // Default Constructor
       public Employee()
       {
            this.id = 0;
            this.name = "Anonymous";
       }

       // Parameterized Constructor
       public Employee(int i, string n)
       {
            this.id = i;
            this.name = n;
       }

       public void display()
       {
           Console.WriteLine("Employee id:" + this.id + " name:" + this.name);
       }
}

public static void Main(string[] args)
{

       Console.WriteLine("Making Object Of Employee Class");
           
       Employee employee = new Employee();
       employee.Id = 10;
       employee.Name = "Osama";
                   
       employee.display(); //call to Employee class display() method
}

 You can see in above example that “id” and “name” are declared as private so you can only access them via their setters/getters.

0 comments: