C Sharp Programming/Encapsulation2

Properties
Properties encapsulate the control of an object's state.

For example, the following  class encapsulates a customer's name:

Customer {   // "private" prevents access of _name outside the Customer class: _name; // The following property allows programmatic changes to _name: Name {       { ._name = ; } { ._name; } } }

The above  property has three important parts: the declaration, the set accessor, and the get accessor.

Property declaration
Name

The access modifier determines who can manipulate this data. Properties can be scoped as, , , or.

The type determines what kind of type it can accept or return.

The property name declares the name used to access the property.

Accessors
Setting the  property for the   class is done through the set accessor, defined using the  keyword.

Similarly, the keyword creates a get accessor to encapsulate the logic to perform when clients retrieve the value of the property.

Above, the simple set accessor and get accessor make property behave very much like a simple field. That may not be the desired behavior. If not, we can add logic to check the value passed into the accessor:

Name {            {                    ( != null) ._name = ; }            {                                      (._name != null) ._name; "John Doe"; }       }

Above, if the client requests to set the value to, the set accessor does not change the field. Also, if the  field hasn't yet been set, the get accessor returns a default value.

Using properties
Clients can use property much like they use simple class fields:

Customer customer = Customer; // this will not set the data. customer.Name = ""; // since the field is not yet set, this will print out: "John Doe" System.Console.WriteLine(customer.Name); customer.Name = "Marissa"; System.Console.WriteLine(customer.Name);

The above code prints the following:

John Doe Marissa

Accessibility levels
The various accessibility levels C# provides are, from most public to least: If no accessibility level is specified, a default level is used. They are:

Note: namespace-level elements (e.g. a class declared directly under a namespace) cannot be declared as stricter than internal.