ENCAPSULATION
IN C#
ENCAPSULATION
• Encapsulation is one of the four fundamental OOP concepts. The
other three are inheritance, polymorphism, and abstraction.
• Encapsulation in C# is a mechanism of wrapping the data
(variables) and code acting on the data (methods or properties)
together as a single unit.
• In encapsulation, the variables of a class will be hidden from other
classes, and can be accessed only through the methods or
properties of their current class. Therefore, it is also known as
data hiding.
ENCAPSULATION
• In a different way, encapsulation is a protective shield that
prevents the data from being accessed by the code outside this
shield.
• Encapsulation is the procedure of encapsulating data and functions
into a single unit (called class)
ENCAPSULATION
• To achieve encapsulation in C# −
• Declare the variables of a class as private.
• Provide public setter and getter methods or properties to modify
and view the variables values.
BENEFITS OF ENCAPSULATION
• The fields of a class can be made read-only or write-only.
• A class can have total control over what is stored in its fields.
WHY DO WE NEED ENCAPSULATION
• The need of encapsulation is to protect or prevent the code (data)
from accidental corruption due to the silly little errors that we are
all prone to make.