Friday, 4 March 2016

Encapsulation in C#

Encapsulation in working

As I mentioned in my previous post that encapsulation has much to do with hiding the field-data of the code. Now the question arises why we want to hide field-data ? 
The answer is: in every class we build, we declare field-data which represents the state of the class at any point and we don't want other classes to change the field-data directly, one of the reason could be that we want certain conditions to be fulfilled before committing any change to field-data. A very simple example can be as follows:
 Suppose you have one class Company

class Company
{
// field-data
public string nameOfCompany;

//some methods
}

class Program
{
public static void Main(string[] args)
{

Company objRef = new Company();
objeRef.nameOfCompany = "132134";
}
}

It can be clearly seen that we're unable to check before data is assigned to field-data 'nameOfCompany' because it's declared as public which means any other class ( class Program here )  can access it directly.

It's not at all recommended to declare field-data as public because you might not want it be changed directly by others without fulfilling certain terms and conditions. e..g in the above code conditions for nameOfCompany field-data could be:

a.) character length should not be more than 256 characters.
b.) name should not contain numerals etc.

We could have made this code more promising by making field-data 'nameOfCompany' private and defined a special method to assign value for it.

e.g. new version of class Company could have been as follows:


class Company
{
// made field-data private
private string nameOfCompany;

public void setName( string name)
{
if(name.Length < 256)
{
nameOfCompany = name;
}
else
{
Console.WriteLine("Sorry name exceeds the character limit");
}
}

//some methods
}

As clearly seen above updated Company class, 'nameOfCompany' is made private, therefore it can't be accessed directly, if some class( e.g. Program class here ) has to assign 'nameOfCompany' some value, it can be done through public method setName(string name) method, which checks a condition before assigning the value to 'nameOfCompany'.

This is how we enforce the concept of encapsulation by hiding our field-data ( i.e. 'nameOfCompany' here ) from outside the class and exposing the method with conditions to be fulfilled before doing any manipulation to the field-data.

2 comments: