Encapsulation in C#

What is encapsulation and how to use encapsulation with C#


Category: C# Tags: C#


Encapsulation

    Binding related variables and actions in a common place is called encapsulation. In other terms there is a container which can contain some related data and their actions(like access methods or operations on those variables) in a common place like a student class having student name, age etc and also some actions to access name and age.

public class Student
{
  string Name;
  int Age;
public string GetName() { return Name; } public void SetName(string name) { Name = name; }
public int GetAge() { return Age;}
public void SetAge(int age) { Age = age; } }

        In above example we are having a class Student which has 2 variables name and age with their access methods. We can make an object of this class and can store a student's name and age in that object.

static void Main(string[] args)
{
Student s1 = new Student();
Student s2 = new Student();

s1.SetName("Nikhil");
s1.SetAge(16);
s2.SetName("Alex");
s2.SetAge(26);

Console.WriteLine("Student1 Name: " + s1.GetName());
Console.WriteLine("Student1 Age: " + s1.GetAge());
Console.WriteLine("Student2 Name :" + s2.GetName());
Console.WriteLine("Student2 Age: " + s2.GetAge());
Console.ReadLine();
}

Output

Student1 Name: Nikhil

Student1 Age: 16

Student2 Name: Alex

Student2 Age: 26


Like 0 People
Last modified on 30 September 2018
Nikhil Joshi

Nikhil Joshi
Ceo & Founder at Dotnetlovers
Atricles: 132
Questions: 9
Given Best Solutions: 9 *

Comments:

No Comments Yet

You are not loggedin, please login or signup to add comments:

Existing User

Login via:

New User



x