Previous Page
Next Page

Chapter 14
Implementing Properties to Access Attributes
After completing this chapter, you will be able to:

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.


Previous Page
Next Page