- •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
278 |
Part III Creating Components |
What Are Properties?
A property is a cross between a field and a method—it looks like a field but acts like a method. You access a property using exactly the same syntax that you use to access a field. However, the compiler automatically translates this fieldlike syntax into calls to accessor methods. A property declaration looks like this:
AccessModifier Type PropertyName
{
get
{
// read accessor code
}
set
{
// write accessor code
}
}
A property can contain two blocks of code, starting with the get and set keywords. The get block contains statements that execute when the property is read, and the set block contains statements that run when the property is written to. The type of the property specifies the type of data read and written by the get and set accessors.
The next code example shows the ScreenPosition structure rewritten by using properties. When reading this code, notice the following:
Lowercase x and y are private fields.
Uppercase X and Y are public properties.
All set accessors are passed the data to be written by using a hidden, built-in parameter named value.
Tip The fields and properties follow the standard Microsoft Visual C# public/private naming convention. Public fields and properties should start with an uppercase letter, but private fields and properties should start with a lowercase letter.
struct ScreenPosition
{
public ScreenPosition(int X, int Y)
{
this.x = rangeCheckedX(X); this.y = rangeCheckedY(Y);
}
Chapter 15 Implementing Properties to Access Fields |
279 |
public int X
{
get { return this.x; }
set { this.x = rangeCheckedX(value); }
}
public int Y
{
get { return this.y; }
set { this.y = rangeCheckedY(value); }
}
private static int rangeCheckedX(int x) { ... } private static int rangeCheckedY(int y) { ... } private int x, y;
}
In this example, a private field directly implements each property, but this is only one way to implement a property. All that is required is that a get accessor return a value of the specified type. Such a value could easily be calculated dynamically rather than being simply retrieved from stored data, in which case there would be no need for a physical field.
Note Although the examples in this chapter show how to define properties for a structure, they are equally applicable to classes; the syntax is the same.
Using Properties
When you use a property in an expression, you can use it in a read context (when you are
reading its value) and in a write context (when you are modifying its value). The following example shows how to read values from the X and Y properties of a ScreenPosition structure:
ScreenPosition origin = new ScreenPosition(0, 0);
int |
xpos |
= |
origin.X; |
// |
calls |
origin.X.get |
int |
ypos |
= |
origin.Y; |
// |
calls |
origin.Y.get |
Notice that you access properties and fields by using the same syntax. When you use a property in a read context, the compiler automatically translates your fieldlike code into a call to the get accessor of that property. Similarly, if you use a property in a write context, the compiler automatically translates your fieldlike code into a call to the set accessor of that property:
origin.X = 40; // calls origin.X.set, with value set to 40 origin.Y = 100; // calls origin.Y.Set, with value set to 100
The values being assigned are passed in to the set accessors by using the value variable, as described in the preceding section. The runtime does this automatically.
280 Part III Creating Components
It’s also possible to use a property in a read/write context. In this case, both the get accessor and the set accessor are used. For example, the compiler automatically translates statements such as the following into calls to the get and set accessors:
origin.X += 10;
Tip You can declare static properties in the same way that you can declare static fields and methods. Static properties are accessed by using the name of the class or structure rather than an instance of the class or structure.
Read-Only Properties
You’re allowed to declare a property that contains only a get accessor. In this case, you
can use the property only in a read context. For example, here’s the X property of the ScreenPosition structure declared as a read-only property:
struct ScreenPosition
{
...
public int X
{
get { return this.x; }
}
}
The X property does not contain a set accessor; therefore, any attempt to use X in a write context will fail. For example:
origin.X = 140; // compile-time error
Write-Only Properties
Similarly, you can declare a property that contains only a set accessor. In this case, you
can use the property only in a write context. For example, here’s the X property of the ScreenPosition structure declared as a write-only property:
struct ScreenPosition
{
...
public int X
{
set { this.x = rangeCheckedX(value); }
}
}
Chapter 15 Implementing Properties to Access Fields |
281 |
The X property does not contain a get accessor; any attempt to use X in a read context will fail. For example:
Console.WriteLine(origin.X); |
// compile-time error |
|
origin.X = 200; |
// |
compiles OK |
origin.X += 10; |
// |
compile-time error |
Note Write-only properties are useful for secure data such as passwords. Ideally, an application that implements security should allow you to set your password but should never allow you to read it back. A login method should compare a user-supplied string with the stored password and return only an indication of whether they match.
Property Accessibility
You can specify the accessibility of a property (public, private, or protected) when you declare
it. However, it is possible within the property declaration to override the property accessibility for the get and set accessors. For example, the version of the ScreenPosition structure shown here defines the set accessors of the X and Y properties as private. (The get accessors are public, because the properties are public.)
struct ScreenPosition
{
...
public int X
{
get { return this.x; }
private set { this.x = rangeCheckedX(value); }
}
public int Y
{
get { return this.y; }
private set { this.y = rangeCheckedY(value); }
}
...
private int x, y;
}
You must observe some rules when defining accessors with different accessibility from one another:
You can change the accessibility of only one of the accessors when you define it. It wouldn’t make much sense to define a property as public only to change the
accessibility of both accessors to private anyway!
The modifier must not specify an accessibility that is less restrictive than that of the property. For example, if the property is declared as private, you cannot specify
the read accessor as public. (Instead, you would make the property public and make the read accessor private.)