- •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 13 Creating Interfaces and Defining Abstract Classes |
247 |
Implementing an Extensible Framework
In the following exercise, you will familiarize yourself with a hierarchy of interfaces and
classes that together implement a simple framework for reading a C# source file and classifying its contents into tokens (identifiers, keywords, operators, and so on). This framework
performs some of the tasks that a typical compiler might perform. The framework provides a mechanism for “visiting” each token in turn, to perform specific tasks. For example, you could create:
A displaying visitor class that displays the source file in a rich text box.
A printing visitor class that converts tabs to spaces and aligns braces correctly.
A spelling visitor class that checks the spelling of each identifier.
A guideline visitor class that checks that public identifiers start with a capital letter and that interfaces start with the capital letter I.
A complexity visitor class that monitors the depth of the brace nesting in the code.
A counting visitor class that counts the number of lines in each method, the number of members in each class, and the number of lines in each source file.
Note This framework implements the Visitor pattern, first documented by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides in Design Patterns: Elements of Reusable Object-Oriented Software (Addison Wesley Longman, 1995).
Understand the inheritance hierarchy and its purpose
1.Start Microsoft Visual Studio 2008 if it is not already running.
2.Open the Tokenizer project, located in the \Microsoft Press\Visual CSharp Step by Step\ Chapter 13\Tokenizer folder in your Documents folder.
3.Display the SourceFile.cs file in the Code and Text Editor window.
The SourceFile class contains a private array field named tokens that looks like this and is essentially a hard-coded version of a source file that has already been parsed and tokenized:
private IVisitableToken[] tokens =
{
new KeywordToken(“using”), new WhitespaceToken(“ “),
new IdentifierToken(“System”), new PunctuatorToken(“;”),
...
};
248 Part II Understanding the C# Language
The tokens array contains a sequence of objects that all implement the IVisitableToken interface (which is explained shortly). Together, these tokens simulate the tokens of a
simple “hello, world” source file. (A complete compiler would parse a source file, identify the type of each token, and dynamically create the tokens array. Each token would be created using the appropriate class type, typically through a switch statement.) The SourceFile class also contains a public method named Accept. The SourceFile.Accept method has a single parameter of type ITokenVisitor. The body of the SourceFile.Accept method iterates through the tokens, calling their Accept methods. The Token.Accept
method will process the current token in some way, according to the type of the token:
public void Accept(ITokenVisitor visitor)
{
foreach (IVisitableToken token in tokens)
{
token.Accept(visitor);
}
}
In this way, the visitor parameter “visits” each token in sequence. The visitor parameter is an instance of some visitor class that processes the token that the visitor object visits. When the visitor object processes the token, the token’s own class methods come into
play.
4.Display the IVisitableToken.cs file in the Code and Text Editor window.
This file defines the IVisitableToken interface. The IVisitableToken interface inherits from two other interfaces, the IVisitable interface and the IToken interface, but does not define any methods of its own:
interface IVisitableToken : IVisitable, IToken
{
}
5.Display the IVisitable.cs file in the Code and Text Editor window.
This file defines the IVisitable interface. The IVisitable interface declares a single method named Accept:
interface IVisitable
{
void Accept(ITokenVisitor visitor);
}
Each object in the array of tokens inside the SourceFile class is accessed using the IVisitableToken interface. The IVisitableToken interface inherits the Accept method, and each token implements the Accept method. (Recall that each token must implement the Accept method because any class that inherits from an interface must implement all the
methods in the interface.)
6. On the View menu, click Class View.
Chapter 13 Creating Interfaces and Defining Abstract Classes |
249 |
The Class View window appears in the pane used by Solution Explorer. This window displays the namespaces, classes, and interfaces defined by the project.
7.In the Class View window, expand the Tokenizer project, and then expand the {} Tokenizer namespace. The classes and interfaces in this namespace are listed. Notice the different icons used to distinguish interfaces from classes.
Expand the IVisitableToken interface, and then expand the Base Types node. The interfaces that the IVisitableToken interface extends (IToken and IVisitable) are displayed, like this:
8.In the Class View window, right-click the IdentifierToken class, and then click Go To Definition to display this class in the Code and Text Editor window. (It is actually located in SourceFile.cs.)
The IdentifierToken class inherits from the DefaultTokenImpl abstract class and the IVisitableToken interface. It implements the Accept method as follows:
void IVisitable.Accept(ITokenVisitor visitor)
{
visitor.VisitIdentifier(this.ToString());
}
Note The VisitIdentifier method processes the token passed to it as a parameter in whatever way the visitor object sees fit. In the following exercise, you will provide an implementation of the VisitIdentifier method that simply renders the token in a particular
color.
The other token classes in this file follow a similar pattern.
250Part II Understanding the C# Language
9.In the Class View window, right-click the ITokenVisitor interface, and then click Go To Definition. This action displays the ITokenVisitor.cs source file in the Code and Text Editor window.
The ITokenVisitor interface contains one method for each type of token. The result
of this hierarchy of interfaces, abstract classes, and classes is that you can create a class that implements the ITokenVisitor interface, create an instance of this class, and pass this instance as the parameter to the Accept method of a SourceFile object. For example:
class MyVisitor : ITokenVisitor
{
public void VisitIdentifier(string token)
{
...
}
public void VisitKeyword(string token)
{
...
}
}
...
class Program
{
static void Main()
{
SourceFile source = new SourceFile(); MyVisitor visitor = new MyVisitor(); source.Accept(visitor);
}
}
The code in the Main method will result in each token in the source file calling the matching method in the visitor object.
In the following exercise, you will create a class that derives from the ITokenVisitor interface and whose implementation displays the tokens from our hard-coded source file in a rich text box in color syntax (for example, keywords in blue) by using the “visitor” mechanism.
Write the ColorSyntaxVisitor class
1.In Solution Explorer (click the Solution Explorer tab below the Class View window), double-click Window1.xaml to display the Color Syntax form in the Design View window.
Chapter 13 Creating Interfaces and Defining Abstract Classes |
251 |
You will use this form to test the framework. This form contains a button for opening a file to be tokenized and a rich text box for displaying the tokens:
The rich text box in the middle of the form is named codeText, and the button is named
Open.
Note A rich text box is like an ordinary text box except that it can display formatted content rather than simple, unformatted text.
2.Right-click the form, and then click View Code to display the code for the form in the
Code and Text Editor window.
3.Locate the openClick method.
This method is called when the user clicks the Open button. You must implement this method so that it displays the tokens defined in the SourceFile class in the rich text box, by using a ColorSyntaxVisitor object. Add the code shown here in bold to the openClick method:
private void openClick(object sender, RoutedEventArgs e)
{
SourceFile source = new SourceFile();
ColorSyntaxVisitor visitor = new ColorSyntaxVisitor(codeText); source.Accept(visitor);
}
Remember that the Accept method of the SourceFile class iterates through all the
tokens, processing each one by using the specified visitor. In this case, the visitor is the ColorSyntaxVisitor object, which will render each token in color.
Note In the current implementation, the Open button uses just data that is hard-coded in the SourceFile class. In a fully functional implementation, the Open button would prompt
the user for the name of a text file and then parse and tokenize it into the format shown in the SourceFile class before calling the Accept method.
252Part II Understanding the C# Language
4.Open the ColorSyntaxVisitor.cs file in the Code and Text Editor window.
The ColorSyntaxVisitor class has been partially written. This class implements the ITokenVisitor interface and already contains two fields and a constructor to initialize a reference to the rich text box, named target, used to display tokens. Your task is to implement the methods inherited from the ITokenVisitor interface and also create a method that will write the tokens to the rich text box.
5.In the Code and Text Editor window, add the Write method to the ColorSyntaxVisitor class exactly as follows:
private void Write(string token, SolidColorBrush color)
{
target.AppendText(token);
int offsetToStartOfToken = -1 * token.Length - 2; int offsetToEndOfToken = -2;
TextPointer start = target.Document.ContentEnd.GetPositionAtOffset(offsetToStartOfToken);
TextPointer end = target.Document.ContentEnd.GetPositionAtOffset(offsetToEndOfToken);
TextRange text = new TextRange(start, end); text.ApplyPropertyValue(TextElement.ForegroundProperty, color);
}
This code appends each token to the rich text box identified by the target variable using the specified color. The two TextPointer variables, start and end, indicate where the
new token starts and ends in the rich text box control. (Don’t worry about how these
positions are calculated. If you’re wondering, they are negative values because they are offset from the ContentEnd property.) The TextRange variable text obtains a reference
to the portion of the text in the rich text box control displaying the newly appended token. The ApplyPropertyValue method sets the color of this text to the color specified
as the second parameter.
Each of the various “visit” methods in the ColorSyntaxVisitor class will call this Write method with an appropriate color to display color-coded results.
6.In the Code and Text Editor window, add the following methods that implement the
ITokenVisitor interface to the ColorSyntaxVisitor class. Specify Brushes.Blue for keywords, Brushes.Green for StringLiterals, and Brushes.Black for all other methods. (Brushes is a class defined in the System.Windows.Media namespace.) Notice that this code implements the interface explicitly; it qualifies each method with the interface name.
void ITokenVisitor.VisitComment(string token)
{
Write(token, Brushes.Black);
}
void ITokenVisitor.VisitIdentifier(string token)
{
Write(token, Brushes.Black);
Chapter 13 Creating Interfaces and Defining Abstract Classes |
253 |
}
void ITokenVisitor.VisitKeyword(string token)
{
Write(token, Brushes.Blue);
}
void ITokenVisitor.VisitOperator(string token)
{
Write(token, Brushes.Black);
}
void ITokenVisitor.VisitPunctuator(string token)
{
Write(token, Brushes.Black);
}
void ITokenVisitor.VisitStringLiteral(string token)
{
Write(token, Brushes.Green);
}
void ITokenVisitor.VisitWhitespace(string token)
{
Write(token, Brushes.Black);
}
It is the class type of the token in the token array that determines which of these methods is called through the token’s override of the Token.Accept method.
Tip You can either type these methods into the Code and Text Editor window directly or
use Visual Studio 2008 to generate default implementations for each one and then modify the method bodies with the appropriate code. To do this, right-click the ITokenVisitor identifier in the class definition sealed class, ColorSyntaxVisitor : ITokenVisitor. On the shortcut menu, point to Implement Interface and then click Implement Interface Explicitly. Each method will contain a statement that throws a NotImplementedException. Replace this
code with that shown here.
7.On the Build menu, click Build Solution. Correct any errors, and rebuild if necessary.
8.On the Debug menu, click Start Without Debugging. The Color Syntax form appears.
9.On the form, click Open.
254 |
Part II Understanding the C# Language |
The dummy code is displayed in the rich text box, with keywords in blue and string literals in green.
10. Close the form, and return to Visual Studio 2008.
Generating a Class Diagram
The Class View window is useful for displaying and navigating the hierarchy of classes and interfaces in a project. Visual Studio 2008 also enables you to generate class diagrams that depict this same information graphically. (You can also use a class diagram to add new classes and interfaces and to define methods, properties, and other class members.)
Note This feature is not available in Visual C# 2008 Express Edition.
To generate a new class diagram, on the Project menu, click Add New Item. In the Add New Item dialog box, select the Class Diagram template, and then click Add. This action
will generate an empty diagram, and you can create new types by dragging items from the Class Designer category in the Toolbox. You can generate a diagram of all exist-
ing classes by dragging them individually from the Class View window or by dragging the namespace to which they belong. The diagram shows the relationships between the classes and interfaces, and you can expand the definition of each class to show its contents. You can drag the classes and interfaces around to make the diagram more readable, as shown in the image on the following page.
