Encapsulation

Encapsulation is another fundamental concept in OOP where the details of a class, that is, the attributes and methods, can be visible or not visible outside the object. With encapsulation, a developer is providing guidance on how a class should be used as well as helping to prevent a class from being handled incorrectly. For example, let's say we wanted to only allow adding PetAnimal objects by using the AddPet(PetAnimal) method. We would do this by having the PetOwner class's AddPet(PetAnimal) method available while having the Pets attribute restricted to anything outside the PetAnimal class. In C#, this is possible by making the Pets attribute private. One reason for doing this would be if additional logic was required whenever a PetAnimal class was added, such as logging or validating that the PetOwner class could have a pet.

C# supports different levels of access that can be set on an item. An item could be a class, a class's attribute or method, or an enumeration:

In the following diagram, access modifiers have been applied to PetAnimal:

As an example, the name of the pet and the color were made private to prevent access from outside the PetAnimal class. In this example, we are restricting the PetName and PetColor properties so only the PetAnimal class can access them in order to ensure that only the base class, PetAnimal, can change their values. The constructor of PetAnimal was protected to ensure only a child class could access it. In this application, only classes within the same library as the Dog class have access to the RegisterInObedienceSchool() method.