Tools of encapsulation in C#, access modifiers in C#

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 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 tools in C#

Encapsulation in C# is implemented with different levels of access to object data that can be specified using the following access modifiers on members (field, property, method, event, delegate, etc) of a class:

  • Public: Access to class member from all code in the program.
  • Private: Access to class member from only members of the same class.
  • Protected: Access to class member from members of same class and its derived classes.
  • Internal: Access to class member from current assembly.
  • Protected Internal: Access to class member from current assembly and types derived from containing class.

Also, C# allows encapsulation of data through the use of properties. Property has getter (to get data) and setter (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. A property provides a single point of access to an object's "set" and "get" values.

Short answer

  • Encapsulation refers to an object's ability to hide data and behavior that are not necessary to its user.
  • C# allows encapsulation through use of access modifiers: private, protected, public, internal, protected internal.
  • In addition, C# properties provide level of indirection through hiding data behind getters and setters.

Similar articles

Comments