Data Structures and Algorithms
with Object-Oriented Design Patterns in C# |
A C# property defines one or two methods for accessing an object. A property that provides a get accessor can be used to access the contents of an object. A property that provides a set accessor can be used to modify an object.
An get accessor is a method that accesses the contents of an object but does not modify that object. In the simplest case, a get accessor just returns the value of one of the fields. In general, a get accessor performs some computation using the fields as long as that computation does not modify any of the fields.
A set accessor is a method that modifies an object. A method that modifies an object is also known as a mutator . In the simplest case, a set accessor modifies a single field of an object. In general, a set accessor may modify any number of the fields of an object.
Program defines two more properties of the Complex class--getR and Theta. The R and Theta properties provide get and set accessors that access a complex number using polar coordinates .
Program: Complex class R and Theta properties.
By defining suitable accessors, it is possible to hide the implementation of the class from the user of that class. Consider the following statements:
Console.WriteLine(c.real); Console.WriteLine(c.Real);The first statement depends on the implementation of the Complex class. If we change the implementation of the class from the one given (which uses rectangular coordinates) to one that uses polar coordinates, then the first statement above must also be changed. On the other hand, the second statement does not need to be modified, provided we reimplement the Real property when we switch to polar coordinates.