C Sharp Programming/Encapsulation2
| A Wikibookian suggests that this book or chapter be merged into C Sharp Programming/Encapsulation.
Please discuss whether or not this merge should happen on the discussion page.
Properties encapsulate the control of an object's state.
For example, the following
Customer class encapsulates a customer's name:
Name property has three important parts: the declaration, the set accessor, and the get accessor.
The type determines what kind of type it can accept or return.
The property name declares the name used to access the property.
Name property for the
Customer class is done through the set accessor, defined using the set keyword.
Similarly, the get 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 set accessor:
Above, if the client requests to set the value to null, the set accessor does not change the field. Also, if the
_name field hasn't yet been set, the get accessor returns a default value.
Clients can use property much like they use simple class fields:
Customer customer = new 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
The various accessibility levels C# provides are, from most public to least:
|internal||The containing assembly.|
|protected internal||The containing assembly or types derived from the containing class.|
|protected||The containing class or types derived from it.|
|private||The containing type.|
If no accessibility level is specified, a default level is used. They are:
|namespace||public (and the only allowed)|
Note: namespace-level elements (e.g. a class declared directly under a namespace) cannot be declared as stricter than internal.