Chapter 14: Implementing Properties to Access Attributes


Chapter 14

Implementing Properties to Access Attributes

After completing this chapter, you will be able to:

  • Encapsulate logical fields by using properties.

  • Control read access to properties by declaring get accessors.

  • Control write access to properties by declaring set accessors.

  • Create interfaces that declare properties.

  • Implement interfaces containing properties, by using structs and classes.

The first two parts of this book have introduced the core syntax of the C# language, and shown you how to use C# to build new types, such as structs, enums, and classes. You have also seen how the runtime manages the memory used by variables and objects when a program runs, and you should now understand the lifecycle of C# objects. The chapters in Part III, “Creating Components,” build on this information, showing you how to use C# to create reusable components—functional classes that you can reuse in many different applications.

This chapter looks at how to define and use properties to hide fields in a class. Previous chapters have emphasized that you should make the fields in a class private, and provide methods to store values in them, or retrieve their values. While this provides safe and controlled access to fields, the syntax for accessing a field in this way is unnatural. When you want to read or write a variable you normally use an assignment statement, so calling a method to achieve the same effect on a field (which is, after all, just a variable) feels a little clumsy. Properties are designed to alleviate this awkwardness.




Microsoft Visual C# 2005 Step by Step
Microsoft® Visual C#® 2005 Step by Step (Step By Step (Microsoft))
ISBN: B002CKYPPM
EAN: N/A
Year: 2005
Pages: 183
Authors: John Sharp

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net