- •Contents at a Glance
- •Table of Contents
- •Acknowledgments
- •Introduction
- •Who This Book Is For
- •Finding Your Best Starting Point in This Book
- •Conventions and Features in This Book
- •Conventions
- •Other Features
- •System Requirements
- •Code Samples
- •Installing the Code Samples
- •Using the Code Samples
- •Support for This Book
- •Questions and Comments
- •Beginning Programming with the Visual Studio 2008 Environment
- •Writing Your First Program
- •Using Namespaces
- •Creating a Graphical Application
- •Chapter 1 Quick Reference
- •Understanding Statements
- •Identifying Keywords
- •Using Variables
- •Naming Variables
- •Declaring Variables
- •Working with Primitive Data Types
- •Displaying Primitive Data Type Values
- •Using Arithmetic Operators
- •Operators and Types
- •Examining Arithmetic Operators
- •Controlling Precedence
- •Using Associativity to Evaluate Expressions
- •Associativity and the Assignment Operator
- •Incrementing and Decrementing Variables
- •Declaring Implicitly Typed Local Variables
- •Chapter 2 Quick Reference
- •Declaring Methods
- •Specifying the Method Declaration Syntax
- •Writing return Statements
- •Calling Methods
- •Specifying the Method Call Syntax
- •Applying Scope
- •Overloading Methods
- •Writing Methods
- •Chapter 3 Quick Reference
- •Declaring Boolean Variables
- •Using Boolean Operators
- •Understanding Equality and Relational Operators
- •Understanding Conditional Logical Operators
- •Summarizing Operator Precedence and Associativity
- •Using if Statements to Make Decisions
- •Understanding if Statement Syntax
- •Using Blocks to Group Statements
- •Cascading if Statements
- •Using switch Statements
- •Understanding switch Statement Syntax
- •Following the switch Statement Rules
- •Chapter 4 Quick Reference
- •Using Compound Assignment Operators
- •Writing while Statements
- •Writing for Statements
- •Understanding for Statement Scope
- •Writing do Statements
- •Chapter 5 Quick Reference
- •Coping with Errors
- •Trying Code and Catching Exceptions
- •Handling an Exception
- •Using Multiple catch Handlers
- •Catching Multiple Exceptions
- •Using Checked and Unchecked Integer Arithmetic
- •Writing Checked Statements
- •Writing Checked Expressions
- •Throwing Exceptions
- •Chapter 6 Quick Reference
- •The Purpose of Encapsulation
- •Controlling Accessibility
- •Working with Constructors
- •Overloading Constructors
- •Understanding static Methods and Data
- •Creating a Shared Field
- •Creating a static Field by Using the const Keyword
- •Chapter 7 Quick Reference
- •Copying Value Type Variables and Classes
- •Understanding Null Values and Nullable Types
- •Using Nullable Types
- •Understanding the Properties of Nullable Types
- •Using ref and out Parameters
- •Creating ref Parameters
- •Creating out Parameters
- •How Computer Memory Is Organized
- •Using the Stack and the Heap
- •The System.Object Class
- •Boxing
- •Unboxing
- •Casting Data Safely
- •The is Operator
- •The as Operator
- •Chapter 8 Quick Reference
- •Working with Enumerations
- •Declaring an Enumeration
- •Using an Enumeration
- •Choosing Enumeration Literal Values
- •Choosing an Enumeration’s Underlying Type
- •Working with Structures
- •Declaring a Structure
- •Understanding Structure and Class Differences
- •Declaring Structure Variables
- •Understanding Structure Initialization
- •Copying Structure Variables
- •Chapter 9 Quick Reference
- •What Is an Array?
- •Declaring Array Variables
- •Creating an Array Instance
- •Initializing Array Variables
- •Creating an Implicitly Typed Array
- •Accessing an Individual Array Element
- •Iterating Through an Array
- •Copying Arrays
- •What Are Collection Classes?
- •The ArrayList Collection Class
- •The Queue Collection Class
- •The Stack Collection Class
- •The Hashtable Collection Class
- •The SortedList Collection Class
- •Using Collection Initializers
- •Comparing Arrays and Collections
- •Using Collection Classes to Play Cards
- •Chapter 10 Quick Reference
- •Using Array Arguments
- •Declaring a params Array
- •Using params object[ ]
- •Using a params Array
- •Chapter 11 Quick Reference
- •What Is Inheritance?
- •Using Inheritance
- •Base Classes and Derived Classes
- •Calling Base Class Constructors
- •Assigning Classes
- •Declaring new Methods
- •Declaring Virtual Methods
- •Declaring override Methods
- •Understanding protected Access
- •Understanding Extension Methods
- •Chapter 12 Quick Reference
- •Understanding Interfaces
- •Interface Syntax
- •Interface Restrictions
- •Implementing an Interface
- •Referencing a Class Through Its Interface
- •Working with Multiple Interfaces
- •Abstract Classes
- •Abstract Methods
- •Sealed Classes
- •Sealed Methods
- •Implementing an Extensible Framework
- •Summarizing Keyword Combinations
- •Chapter 13 Quick Reference
- •The Life and Times of an Object
- •Writing Destructors
- •Why Use the Garbage Collector?
- •How Does the Garbage Collector Work?
- •Recommendations
- •Resource Management
- •Disposal Methods
- •Exception-Safe Disposal
- •The using Statement
- •Calling the Dispose Method from a Destructor
- •Making Code Exception-Safe
- •Chapter 14 Quick Reference
- •Implementing Encapsulation by Using Methods
- •What Are Properties?
- •Using Properties
- •Read-Only Properties
- •Write-Only Properties
- •Property Accessibility
- •Understanding the Property Restrictions
- •Declaring Interface Properties
- •Using Properties in a Windows Application
- •Generating Automatic Properties
- •Initializing Objects by Using Properties
- •Chapter 15 Quick Reference
- •What Is an Indexer?
- •An Example That Doesn’t Use Indexers
- •The Same Example Using Indexers
- •Understanding Indexer Accessors
- •Comparing Indexers and Arrays
- •Indexers in Interfaces
- •Using Indexers in a Windows Application
- •Chapter 16 Quick Reference
- •Declaring and Using Delegates
- •The Automated Factory Scenario
- •Implementing the Factory Without Using Delegates
- •Implementing the Factory by Using a Delegate
- •Using Delegates
- •Lambda Expressions and Delegates
- •Creating a Method Adapter
- •Using a Lambda Expression as an Adapter
- •The Form of Lambda Expressions
- •Declaring an Event
- •Subscribing to an Event
- •Unsubscribing from an Event
- •Raising an Event
- •Understanding WPF User Interface Events
- •Using Events
- •Chapter 17 Quick Reference
- •The Problem with objects
- •The Generics Solution
- •Generics vs. Generalized Classes
- •Generics and Constraints
- •Creating a Generic Class
- •The Theory of Binary Trees
- •Building a Binary Tree Class by Using Generics
- •Creating a Generic Method
- •Chapter 18 Quick Reference
- •Enumerating the Elements in a Collection
- •Manually Implementing an Enumerator
- •Implementing the IEnumerable Interface
- •Implementing an Enumerator by Using an Iterator
- •A Simple Iterator
- •Chapter 19 Quick Reference
- •What Is Language Integrated Query (LINQ)?
- •Using LINQ in a C# Application
- •Selecting Data
- •Filtering Data
- •Ordering, Grouping, and Aggregating Data
- •Joining Data
- •Using Query Operators
- •Querying Data in Tree<TItem> Objects
- •LINQ and Deferred Evaluation
- •Chapter 20 Quick Reference
- •Understanding Operators
- •Operator Constraints
- •Overloaded Operators
- •Creating Symmetric Operators
- •Understanding Compound Assignment
- •Declaring Increment and Decrement Operators
- •Implementing an Operator
- •Understanding Conversion Operators
- •Providing Built-In Conversions
- •Creating Symmetric Operators, Revisited
- •Adding an Implicit Conversion Operator
- •Chapter 21 Quick Reference
- •Creating a WPF Application
- •Creating a Windows Presentation Foundation Application
- •Adding Controls to the Form
- •Using WPF Controls
- •Changing Properties Dynamically
- •Handling Events in a WPF Form
- •Processing Events in Windows Forms
- •Chapter 22 Quick Reference
- •Menu Guidelines and Style
- •Menus and Menu Events
- •Creating a Menu
- •Handling Menu Events
- •Shortcut Menus
- •Creating Shortcut Menus
- •Windows Common Dialog Boxes
- •Using the SaveFileDialog Class
- •Chapter 23 Quick Reference
- •Validating Data
- •Strategies for Validating User Input
- •An Example—Customer Information Maintenance
- •Performing Validation by Using Data Binding
- •Changing the Point at Which Validation Occurs
- •Chapter 24 Quick Reference
- •Querying a Database by Using ADO.NET
- •The Northwind Database
- •Creating the Database
- •Using ADO.NET to Query Order Information
- •Querying a Database by Using DLINQ
- •Creating and Running a DLINQ Query
- •Deferred and Immediate Fetching
- •Joining Tables and Creating Relationships
- •Deferred and Immediate Fetching Revisited
- •Using DLINQ to Query Order Information
- •Chapter 25 Quick Reference
- •Using Data Binding with DLINQ
- •Using DLINQ to Modify Data
- •Updating Existing Data
- •Adding and Deleting Data
- •Chapter 26 Quick Reference
- •Understanding the Internet as an Infrastructure
- •Understanding Web Server Requests and Responses
- •Managing State
- •Understanding ASP.NET
- •Creating Web Applications with ASP.NET
- •Building an ASP.NET Application
- •Understanding Server Controls
- •Creating and Using a Theme
- •Chapter 27 Quick Reference
- •Comparing Server and Client Validations
- •Validating Data at the Web Server
- •Validating Data in the Web Browser
- •Implementing Client Validation
- •Chapter 28 Quick Reference
- •Managing Security
- •Understanding Forms-Based Security
- •Implementing Forms-Based Security
- •Querying and Displaying Data
- •Understanding the Web Forms GridView Control
- •Displaying Customer and Order History Information
- •Paging Data
- •Editing Data
- •Updating Rows Through a GridView Control
- •Navigating Between Forms
- •Chapter 29 Quick Reference
- •What Is a Web Service?
- •The Role of SOAP
- •What Is the Web Services Description Language?
- •Nonfunctional Requirements of Web Services
- •The Role of Windows Communication Foundation
- •Building a Web Service
- •Creating the ProductsService Web Service
- •Web Services, Clients, and Proxies
- •Talking SOAP: The Easy Way
- •Consuming the ProductsService Web Service
- •Chapter 30 Quick Reference
Chapter 14 Using Garbage Collection and Resource Management |
267 |
Notice the following features of the Example class:
The class implements the IDisposable interface.
The destructor calls Dispose.
The Dispose method is public and can be called at any time.
The Dispose method can safely be called multiple times. The variable disposed indicates whether the method has already been run. The scarce resource is released only the first time the method runs.
The Dispose method calls the static GC.SuppressFinalize method. This method stops the garbage collector from calling the destructor on this object, because the object has now been finalized.
All the regular methods of the class (such as SomeBehavior) check to see whether the object has already been disposed. If it has, they throw an exception.
Making Code Exception-Safe
In the following exercise, you will rewrite a small piece of code to make the code exceptionsafe. The code opens a text file, reads its contents one line at a time, writes these lines to a text box on a form on the screen, and then closes the text file. However, if an exception arises
as the file is read or as the lines are written to the text box, the call to close the text file will be bypassed. You will rewrite the code to use a using statement instead, ensuring that the
code is exception-safe.
Write a using statement
1.Start Microsoft Visual Studio 2008 if it is not already running.
2.Open the UsingStatement project, located in the \Microsoft Press\Visual CSharp Step by Step\Chapter 14\UsingStatement folder in your Documents folder.
3.On the Debug menu, click Start Without Debugging.
A Windows Presentation Foundation (WPF) form appears.
4.On the form, click Open File.
5.In the Open dialog box, move to the \Microsoft Press\Visual CSharp Step by Step\ Chapter 14\UsingStatement\UsingStatement folder in your Documents folder, and select the Window1.xaml.cs source file.
This is the source file for the application itself.
268Part II Understanding the C# Language
6.Click Open.
The contents of the file are displayed in the form, as shown here:
7.Close the form to return to Visual Studio 2008.
8.Open the Window1.xaml.cs file in the Code and Text Editor window, and then locate the openFileDialogFileOk method.
The method looks like this:
private void openFileDialogFileOk(object sender, System.ComponentModel.CancelEventArgs e)
{
string fullPathname = openFileDialog.FileName; FileInfo src = new FileInfo(fullPathname); fileName.Text = src.Name;
source.Clear();
TextReader reader = new StreamReader(fullPathname); string line;
while ((line = reader.ReadLine()) != null)
{
source.Text += line + “\n”;
}
reader.Close();
}
Chapter 14 Using Garbage Collection and Resource Management |
269 |
The variables fileName, openFileDialog, and source are three private fields of the Window1 class. The problem with this code is that the call to reader.Close is not guaran-
teed to execute. If an exception occurs after opening the file, the method will terminate with an exception, but the file will remain open until the application finishes.
9.Modify the openFileDialogFileOk method, and wrap the code that processes the file in a using statement (including opening and closing braces), as shown in bold here. Remove the statement that closes the TextReader object.
private void openFileDialogFileOk(object sender, System.ComponentModel.CancelEventArgs e)
{
string fullPathname = openFileDialog.FileName; FileInfo src = new FileInfo(fullPathname); fileName.Text = src.Name;
source.Clear();
using (TextReader reader = new StreamReader(fullPathname))
{
string line;
while ((line = reader.ReadLine()) != null)
{
source.Text += line + “\n”;
}
}
}
You no longer need to call reader.Close because it will be invoked automatically by the Dispose method of the StreamReader class when the using statement completes.
This applies whether the using statement finishes naturally or terminates because of an exception.
10.On the Debug menu, click Start Without Debugging.
11.Verify that the application works as before, and then close the form.
If you want to continue to the next chapter:
Keep Visual Studio 2008 running, and turn to Chapter 15. If you want to exit Visual Studio 2008 now:
On the File menu, click Exit. If you see a Save dialog box, click Yes (if you are using Visual Studio 2008) or Save (if you are using Visual C# 2008 Express Edition) and save the project.
270 |
Part II Understanding the C# Language |
|
Chapter 14 Quick Reference |
||
To |
|
Do this |
Write a destructor |
Write a method whose name is the same as the name of the class and is pre- |
|
|
|
fixed with a tilde (~). The method must not have an access modifier (such as |
|
|
public) and cannot have any parameters or return a value. For example: |
|
|
class Example |
|
|
{ |
|
|
~Example() |
|
|
{ |
|
|
... |
|
|
} |
|
|
} |
|
|
|
Call a destructor |
You can’t call a destructor. Only the garbage collector can call a destructor. |
|
|
|
|
Force garbage collection |
Call System.GC.Collect. |
|
(not recommended) |
|
|
Release a resource at a known point in time (but at the risk of memory leaks if an exception interrupts the execution)
Write a disposal method (a method that disposes of a resource) and call it explicitly from the program. For example:
class TextReader
{
...
public virtual void Close()
{
...
}
}
class Example
{
void Use()
{
TextReader reader = ...; // use reader reader.Close();
}
}
Chapter 14 Using Garbage Collection and Resource Management |
271 |
Release a resource at a known point in time in an exception-safe manner (the recommended approach)
Release the resource with a using statement. For example:
class TextReader : IDisposable
{
...
public virtual void Dispose()
{
// calls Close
}
public virtual void Close()
{
...
}
}
class Example
{
void Use()
{
using (TextReader reader = ...)
{
// use reader
}
}
}
Microsoft Visual C# 2008 Step by Step
Part III
Creating Components
In this part:
Chapter 15. Implementing Properties to Access Fields . . . . . . . . . . . . . . . . . . . . 275 Chapter 16. Using Indexers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295 Chapter 17. Interrupting Program Flow and Handling Events. . . . . . . . . . . . . . . 311 Chapter 18. Introducing Generics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333 Chapter 19. Enumerating Collections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355 Chapter 20. Querying In-Memory Data By Using Query Expressions . . . . . . . . 371 Chapter 21. Operator Overloading. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395
273
Chapter 15
Implementing Properties to
Access Fields
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 structures and classes.
Generate properties automatically based on field definitions.
Use properties to initialize objects.
The first two parts of this book have introduced the core syntax of the C# language and have shown you how to use C# to build new types using structures, enumerations, 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 life cycle 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 and to retrieve their values. This approach provides safe and controlled access to fields and enables you to encapsulate additional logic and rules concerning the values that are permitted. However, 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.
275
