17.4. Summary

C# has three programming constructs that do not have direct equivalents in the Java world: properties, indexers, and attributes.

Properties are a façade for an object's attributes or fields. Properties provide get{} and set{} blocks, which are like the accessor and mutator methods. The code in the get{} and set{} blocks is called by the runtime transparently whenever the user of the property sets or gets the value of the property. Properties have the pros and cons shown in Table 17.2.

You should use properties only for wrapping the fields of an object so that the get and set blocks do minimal or no processing in getting and setting the value of the property.

Indexers let you use array-like notation to access a collection of objects. Indexers can be integer- or string-based. A single object can define multiple indexers, and an indexer can be defined with multiple indices. Indexers have the same pros and cons as properties. They simplify the overall look and feel of the code, but if there is CPU- or memory-intensive code in the underlying get{} and set{} blocks, then it could negatively affect the performance of the application depending on how the indexer is used. It is recommended that indexers be used when the get and set blocks of the indexer do minimal or no processing.

Table 17.2. Pros and Cons of C# Properties
ProsCons
Simplify syntax. Properties can be get or set like ordinary programming variables, thereby simplifying the overall look and feel of the code.Properties do not require the user of the property to know anything about the property signature because there is none.Properties simplify syntax by hiding the calls to the code in the get{} and set{} blocks. Placing any CPU- or memory-intensive code in these blocks could result in poor performance of the resulting application depending on how the property is being used.

Properties do not throw any exceptions, and so the user does not know beforehand which exceptions to look out for when using a property.

Properties do not allow for different access modifiers on the get{} and set{} blocks.

Attributes provide a declarative way to dynamically change the behavior of code at runtime. The System.Attribute class also provides an API to programmatically access and change the attribute. Associated with every C# object there is metadata (information about the methods, fields, interfaces, types), and attributes allow you to extend that metadata.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.14.240.178