C Sharp Programming/Encapsulation

Encapsulation is depriving the user of a class of information the user does not need, and preventing the user from manipulating objects in ways not intended by the designer.

A class element having public protection level is accessible to all code anywhere in the program. These methods and properties represent the operations allowed on the class to outside users.

Methods, data members (and other elements) with private protection level represent the internal state of the class (for variables), and operations that are not allowed to outside users. The private protection level is default for all class and struct members. This means that if you do not specify the protection modifier of a method or variable, it is considered as private by the compiler.

For example:

In this example, the public method the class exposes are  and. Internally, they are implemented using the private function that can jump to any height. This operation is not visible to an outside user, so they cannot make the frog jump 100 meters, only 10 or 1. The private method is implemented by changing the value of a private data member, which is also not visible to an outside user. Some private data members are made visible by Properties.

Private
Private members are only accessible within the class itself. A method in another class, even a class derived from the class with private members cannot access the members. If no protection level is specified, class members will default to private.

Protected
Protected members can be accessed by the class itself and by any class derived from that class.

Public
Public members can be accessed by any method in any class.

It is good programming practice not to expose member variables to the outside, unless it is necessary. This is true especially for fields that should only be accessible over accessor and mutator methods (getters and setters). Exceptions are member variables that are constant.

Internal
Internal members are accessible only in the same assembly and invisible outside it. If no protection level is specified for top level classes, they are treated as internal, and can only be accessed within the assembly.

Protected Internal
Protected internal members are accessible from any class derived from that class, or any class within the same assembly. So, it means protected or internal.

Here, an example: