Encapsulation in C#

What is encapsulation and how to use encapsulation with C#

Category: C# Tags: C#


    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();


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


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: 135
Questions: 12
Given Best Solutions: 12 *


No Comments Yet

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

Existing User

Login via:

New User