Tech moves fast! Stay ahead of the curve with Techopedia!
Join nearly 200,000 subscribers who receive actionable tech insights from Techopedia.
Encapsulation, in the context of C#, refers to an object's ability to hide data and behavior that are not necessary to its user. Encapsulation enables a group of properties, methods and other members to be considered a single unit or object.
The following are the benefits of encapsulation:
Encapsulation is used to restrict access to the members of a class so as to prevent the user of a given class from manipulating objects in ways that are not intended by the designer. While encapsulation hides the internal implementation of the functionalities of class without affecting the overall functioning of the system, it allows the class to service a request for functionality and add or modify its internal structure (data or methods) to suit changing requirements.
Encapsulation is also known as information hiding.
Encapsulation in C# is implemented with different levels of access to object data that can be specified using the following access modifiers:
Encapsulation can be illustrated with an example of an Employee object that stores details of that object. By using encapsulation, the Employee object can expose the data (like Name, EmployeeID, etc.) and methods (like GetSalary) necessary for using the object, while hiding its irrelevant fields and methods from other objects. It is easy to see a situation in which all users could access basic information about an employee while restricting salary information.
C# allows encapsulation of data through the use of accessors (to get data) and mutators (to modify data), which help in manipulating private data indirectly without making it public. Properties are an alternate mechanism for private data to be encapsulated in a C# object and accessed in either read-only mode or in read-write mode. Unlike the accessor and mutator, a property provides a single point of access to an object's "set" and "get" values.
Do you work in the tech industry? Help us learn more about why the gender gap still exists in tech by taking this quick survey! Survey respondents will also be entered to win a $100 Amazon Gift Card!