Close
Close

Encapsulation in C#


Encapsulation is nothing new to what we have read, it is just a concept. It is the way of combining the data and methods inside a class. Thus the data gets hidden from being accessed directly from outside the class. This is similar to a capsule where several medicines are kept inside the capsule thus hiding them from being directly consumed from outside. All the members of a class are private by default, thus preventing them from being accessed from outside the class.

encapsulation

In short, it is just a concept to make all data private and access them using getters and setters. These getters and setters can be our own defined functions or properties with get and set.

Why Encapsulation?


Encapsulation is necessary to keep the details about an object hidden from the users of that object. Details of an object are stored in its data members. This is the reason we make all the member variables of a class private and most of the member methods public. Member variables are made private so that these cannot be directly accessed from outside the class (to hide the details of any object of that class like how the data about the object is implemented) and so most member methods are made public to allow the users to access the data members through those methods.

Benefits of Encapsulation


There are various benefits of encapsulated classes.

  • Encapsulated classes reduce complexity.
  • Help protect our data. A client cannot change an Account's balance if we encapsulate it.
  • Encapsulated classes are easier to change. We can change the privacy of the data according to the requirement without changing the whole program by using access modifiers. For example, if a data member is declared private and we wish to make it directly accessible from anywhere outside the class, we just need to replace the specifier private by public.

Let's take an example of encapsulation with our own methods for getter and setter.

using System;

class Student
{
private string name = "xyz";

public string GetName()
{
  return this.name;
}

public void SetName(string s)
{
  this.name = s;
}
}

class Test
{
static void Main(string[] args)
{
  Student s = new Student();
  s.SetName("xyz");
  Console.WriteLine(s.GetName());
}
}
Output
xyz

Here, we have a private variable name and we defined two public methods - GetName and SetName to return and set the value of the variable name.

We can also use default properties for the same which we studied in the previous chapter.

using System;

class Student
{
public string Name
{
  get;
  set;
}
}

class Test
{
static void Main(string[] args)
{
  Student s = new Student();
  s.Name = "xyz";
  Console.WriteLine(s.Name);
}
}
Output
xyz

Ask Yours
Post Yours
Doubt? Ask question