C Sharp Programming/Encapsulation

From Wikibooks, the open-content textbooks collection

Jump to: navigation, search

Encapsulation is depriving of the user of a class information he does not need, and preventing him 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 which 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:

public class Frog
{
	public void JumpLow() { Jump(1); }
	public void JumpHigh() { Jump(10); }

	void Jump(int height) { _height += height;}

	private int _height = 0;
}

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

Contents

[edit] Protection Levels

[edit] 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.

[edit] Protected

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

[edit] Public

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

[edit] Internal

Internal members are accessible only in the same assembly and invisible outside it.

If no protection level is specified, class members are usually treated as internal. However, nested classes or types will have a different default protection level.

[edit] Protected Internal

Protected internal members are accessible from any class derived from the that class, or any class within the same assembly.