Introduction
This book has existed (in one form or another) since the first edition of C# and the .NET Platformwas published in conjunction with the release of .NET 1.0 Beta 2, circa the summer of 2001. Since
that point, I have been extremely happy and grateful to see that this text was very well received by
the press and, most important, by readers. Over the years it was nominated as a Jolt Award finalist
(I lost . . . crap!) and for the 2003 Referenceware Excellence Award in the programming book category
(I won? Cool!).
Since that point, I have worked to keep the book current with each release of the .NET platform,
including a limited printing of a Special Edition, which introduced the technologies of .NET 3.0
(Windows Presentation Foundation, Windows Communication Foundation, and Windows Workflow
Foundation) as well as offered previews of several forthcoming technologies, which we now know as
LINQ.
The fourth edition of this text, which you hold in your hands, is a massive retelling of the previous
manuscript to account for all of the major changes that are found within .NET 3.5. Not only will
you find numerous brand-new chapters, you will find many of the previous chapters have been
expanded in great detail.
As with the earlier editions, this edition presents the C# programming language and .NET base
class libraries using a friendly and approachable tone. I have never understood the need some
technical authors have to spit out prose that reads more like a GRE vocabulary study guide than a
readable book. As well, this new edition remains focused on providing you with the information you
need to build software solutions today, rather than spending too much time examining esoteric
details that few individuals will ever actually care about.
We’re a Team, You and I
Technology authors write for a demanding group of people (I should know—I’m one of them).You know that building software solutions using any platform (.NET, J2EE, COM, etc.) is extremely
detailed and is very specific to your department, company, client base, and subject matter. Perhaps
you work in the electronic publishing industry, develop systems for the state or local government,
or work at NASA or a branch of the military. Speaking for myself, I have developed children’s educational
software, various n-tier systems, and projects within the medical and financial industries. The
chances are almost 100 percent that the code you write at your place of employment has little to do
with the code I write at mine (unless we happened to work together previously!).
Therefore, in this book, I have deliberately chosen to avoid creating examples that tie the
example code to a specific industry or vein of programming. Given this, I explain C#, OOP, the CLR,
and the .NET 3.5 base class libraries using industry-agnostic examples. Rather than having every
blessed example fill a grid with data, calculate payroll, or whatnot, I’ll stick to subject matter we can
all relate to: automobiles (with some geometric structures and employees thrown in for good measure).
And that’s where you come in.
My job is to explain the C# programming language and the core aspects of the .NET platform
the best I possibly can. As well, I will do everything I can to equip you with the tools and strategies
you need to continue your studies at this book’s conclusion.
Your job is to take this information and apply it to your specific programming assignments.
I obviously understand that your projects most likely don’t revolve around automobiles with pet
names, but that’s what applied knowledge is all about! Rest assured, once you understand the concepts
presented within this text, you will be in a perfect position to build .NET solutions that map to
your own unique programming environment.
An Overview of This Book
Pro C# 2008 and the .NET 3.5 Platform, Fourth Edition is logically divided into eight distinct parts,each of which contains a number of related chapters. If you have read the earlier editions of this
text, you will quickly notice a number of changes. For example, several topics (such as core C# constructs,
object-oriented programming, and platform-independent .NET development) have been
expanded into several dedicated chapters. Furthermore, this edition of the text contains numerous
new chapters to account for .NET 3.0–3.5 programming features (LINQ, WCF, WPF, WF, etc.). Here is
a part-by-part and chapter-by-chapter breakdown of the text.
The Philosophy of .NET
The .NET Solution
What C# Brings to the Table
Additional .NET-Aware Programming Languages
An Overview of .NET Assemblies
Single-File and Multifile Assemblies
The Role of the Common Intermediate Language
The Role of .NET Type Metadata
Understanding the Common Type System
CTS Interface Types
CTS Delegate Types
Understanding the Common Language Specification
Understanding the Common Language Runtime
Hello world
A Sampling of .NET Namespaces
Exploring an Assembly Using ildasm.exe
Deploying the .NET Runtime
The Platform-Independent Nature of .NET
Building C# Applications
The Visual Studio 2008 Command Prompt
Building C# Applications Using csc.exe
Referencing External Assemblies
Working with C# Response Files
Building .NET Applications Using TextPad
Building .NET Applications Using Notepad++
Building .NET Applications Using SharpDevelop
Building .NET Applications Using Visual C# 2008 Express
Building .NET Applications Using Visual Studio 2008
Targeting the .NET Framework Using the New Project Dialog Box
Core C# Programming Constructs
The Anatomy of a Simple C# Program
Variations on the Main() Method
Specifying an Application Error Code
Processing Command-Line Arguments
An Interesting Aside: Some Additional Members of the System.Environment Class
The System.Console Class
Formatting Console Output
System Data Types and C# Shorthand Notation
Variable Declaration and Initialization
Understanding the System.String Type
Defining Verbatim Strings
Narrowing and Widening Data Type Conversions
C# Iteration Constructs
Decision Constructs and the Relational/Equality Operators
The switch Statement
Core C# Programming Constructs, Part II
Methods and Parameter Modifiers
Methods and Parameter Modifiers
The Default Parameter-Passing Behavior
The params Modifier
understanding-member-overloading
Array Manipulation in C#
C# Array Initialization Syntax
Working with Multidimensional Arrays
Arrays As Parameters (and Return Values)
The System.Array Base Class
Understanding the Enum Type
Controlling the Underlying Storage for an Enum
The System.Enum Type
Understanding the Structure Type
Creating Structure Variables
Understanding Value Types and Reference Types
Value Types, References Types, and the Assignment Operator
Value Types Containing Reference Types
Passing Reference Types by Value
Passing Reference Types by Reference
Understanding C# Nullable Types
Working with Nullable Types
The ?? Operator
Defining Encapsulated Class Types
Introducing the C# Class Type
Allocating Objects with the new Keyword
Understanding Class Constructors
The Default Constructor Revisited
The Role of the this Keyword
Chaining Constructor Calls Using this
Observing Constructor Flow
Understanding the static Keyword
Defining Static Methods (and Fields)
Defining Static Data
Defining Static Constructors
Defining Static Classes
Defining the Pillars of OOP
The Role of Encapsulation
The Role of Inheritance
The Role of Polymorphism
C# Access Modifiers
The First Pillar: C#??™s Encapsulation Services
Encapsulation Using Traditional Accessors and Mutators
Encapsulation Using Type Properties
Controlling Visibility Levels of Property Get/Set Statements
Static Properties
Understanding Constant Data
Understanding Read-Only Fields
Understanding Partial Types
Documenting C# Source Code via XML
Understanding Inheritance and Polymorphism
The Basic Mechanics of Inheritance
Regarding Multiple Base Classes
The sealed Keyword
The Second Pillar: The Details of Inheritance
Controlling Base Class Creation with the base Keyword
Keeping Family Secrets: The protected Keyword
Programming for Containment/Delegation
Understanding Nested Type Definitions
The Third Pillar: C#??™s Polymorphic Support
The virtual and override Keywords
Sealing Virtual Members
Understanding Abstract Classes
The Master Parent Class: System.Object
Overriding System.Object.ToString()
Overriding System.Object.Equals()
Overriding System.Object.GetHashCode()
Testing Our Modified Person Class
Understanding Structured Exception Handling
Ode to Errors, Bugs, and Exceptions
The Role of .NET Exception Handling
The Atoms of .NET Exception Handling
The Simplest Possible Example
Throwing a Generic Exception
Catching Exceptions
The Data Property
Processing Multiple Exceptions
The Finally Block
The Result of Unhandled Exceptions
Understanding Object Lifetime
Classes, Objects, and References
The Basics of Object Lifetime
The CIL of new
Setting Object References to null
Understanding Object Generations
The System.GC Type
Forcing a Garbage Collection
Building Finalizable Objects
Overriding System.Object.Finalize()
Building Disposable Objects
Reusing the C# using Keyword
Building Finalizable and Disposable Types
A Formalized Disposal Pattern
Advanced C# Programming Constructs
Understanding Interface Types
Contrasting Interface Types to Abstract Base ClassesContrasting Interface Types to Abstract Base Classes
Defining Custom Interfaces
Implementing an Interface
Invoking Interface Members at the Object Level
Obtaining Interface References: The as Keyword
Interfaces As Parameters
Interfaces As Return Values
Designing Interface Hierarchies
Building Cloneable Objects
AMore Elaborate Cloning Example
Building Comparable Objects (IComparable)
Collections and Generics
The Interfaces of the System.Collections Namespace
The Role of ICollection
The Role of IList
Working with the ArrayList Type
Working with the Stack Type
System.Collections.Specialized Namespace
The Boxing, Unboxing, and System.Object Relationship
The Problem with (Un)Boxing Operations
Delegates, Events, and Lambdas
Understanding the .NET Delegate Type
Defining a Delegate in C#
The System.MulticastDelegate and System.Delegate Base Classes
The Simplest Possible Delegate Example
Investigating a Delegate Object
Retrofitting the Car Type with Delegates
Enabling Multicasting
A More Elaborate Delegate Example
Delegates As Parameters
Analyzing the Delegation Code
Understanding Delegate Covariance
Creating Generic Delegates
Simulating Generic Delegates Without Generics
Understanding C# Events
The Event Keyword
Events Under the Hood
Listening to Incoming Events
Simplifying Event Registration Using Visual Studio 2008
A ???Prim-and-Proper??? Event
The Generic EventHandler
Understanding C# Anonymous Methods
Accessing ???Outer???Variables
Indexers, Operators, and Pointers
Understanding Indexer Methods
Indexing Objects Using String Values
Overloaded Indexer Methods
Internal Representation of Indexer Methods
Overloading Binary Operators
And What of the += and ??“+ Operators?
Overloading Equality Operators
Overloading Comparison Operators
Working with the * and & Operators
Field Access via Pointers (the -> Operator)
C# Preprocessor Directives
C# 2008 Language Features
Understanding Implicitly Typed Local Variables
Understanding Automatic Properties
Understanding Extension Methods
Invoking Extension Methods on an Instance Level
Understanding Partial Methods
A First Look at Partial Methods
Uses of Partial Methods
Understanding Object Initializer Syntax
Initializing Inner Types
Understanding Collection Initialization
Understanding Anonymous Types
The Internal Representation of Anonymous Types
The Implementation of ToString() and GetHashCode()
An Introduction to LINQ
Understanding the Role of LINQ
A First Look at LINQ Query Expressions
LINQ and Implicitly Typed Local Variables
LINQ and Extension Methods
LINQ Queries: An Island unto Themselves?
Transforming Query Results to Array Types
Programming with .NET Assemblies
Introducing .NET Assemblies
Defining Custom Namespaces
A Type??™s Fully Qualified Name
Defining using Aliases
Building and Consuming a Multifile Assembly
Building and Consuming
Understanding Private Assemblies
Configuring Private Assemblies
Understanding Shared Assemblies
Understanding Shared Assemblies
Strongly Naming CarLibrary.dll
Consuming a Shared Assembly
Exploring the Manifest of SharedCarLibClient
Configuring Shared Assemblies
Revisiting the .NET Framework Configuration Utility
Investigating the Internal Composition of the GAC
Understanding Publisher Policy Assemblies
Disabling Publisher Policy
Understanding the
The System.Configuration Namespace
Type Reflection, Late Binding, and Attribute-Based Programming
Viewing (Partial) Metadata for the EngineState Enumeration
Building a Custom Metadata Viewer
Reflecting on Implemented Interfaces
Reflecting on Generic Types
Dynamically Loading Assemblies
Reflecting on Shared Assemblies
Understanding Late Binding
The System.Activator Class
Invoking Methods with No Parameters
Understanding Attributed Programming
Building Custom Attributes
Putting Reflection, Late Binding, and Custom Attributes in Perspective
Building an Extendable Application
Building CommonSnappableTypes.dll
Building the C# Snap-In
Building the Visual Basic Snap-In
Processes, AppDomains, and Object Contexts
Interacting with Processes Under the .NET Platform
Starting and Stopping Processes Programmatically
Understanding .NET Application Domains
Enumerating a Process??™s AppDomains
Programmatically Creating New AppDomains
Building Multithreaded Applications
The Process/AppDomain/Context/Thread Relationship
A Brief Review of the .NET Delegate
Understanding the CLR ThreadPool
The Role of the BackgroundWorker Component
Processing Our Data with the BackgroundWorker Type
Understanding CIL and the Role of Dynamic Assemblies
Reflecting on the Nature of CIL Programming
Examining CIL Directives, Attributes, and Opcodes
Pushing and Popping: The Stack-Based Nature of CIL
Understanding Round-Trip Engineering
The Role of CIL Code Labels
Interacting with CIL:Modifying an *.il File
Building a .NET Assembly with CIL
Building CILCarClient.exe
Understanding Dynamic Assemblies
Introducing the .NET Base Class Libraries
File I/O and Isolated Storage
Working with the Directory Type
Working with the DriveInfo Class Type
The FileInfo.Open() Method
Working with the File Type
Working with FileStreams
Writing to a Text File
Working with StringWriters and StringReaders
Programmatically ???Watching??? Files
Performing Asynchronous File I/O
Understanding the Role of Isolated Storage
Obtaining a Store Using IsolatedStorageFile
Writing Data to Storage
Reading Data from Storage
Isolated Storage in Action: ClickOnce Deployment
Introducing Object Serialization
Understanding Object Serialization
Configuring Objects for Serialization
Public Fields, Private Fields, and Public Properties
Choosing a Serialization Formatter
The IFormatter and IRemotingFormatter Interfaces
Serializing Objects Using the BinaryFormatter
Serializing Collections of Objects
ADO.NET Part I: The Connected Layer
A High-Level Definition of ADO.NET
Abstracting Data Providers Using Interfaces
Increasing Flexibility Using Application Configuration Files
Creating the AutoLot Database
The ADO.NET Data Provider Factory Model
Registered Data Provider Factories
A Complete Data Provider Factory Example
Understanding the Connected Layer of ADO.NET
Working with Data Readers
Creating a Console UI??“Based Front End At this point, our first iteration of the AutoLotDAL.dll data access library is complete. Using this assembly, we can build any sort of front end to display and edit our data (console based, Windows Forms based, Win
Implementing the Main() Method
Implementing the ShowInstructions() Method
Implementing the ListInventory() Method
Implementing the DeleteCar() Method
Implementing the InsertNewCar() Method
Implementing the UpdateCarPetName() Method
Invoking Our Stored Procedure
Asynchronous Data Access Using SqlCommand
Key Members of an ADO.NET Transaction Object
Adding a Transaction Method to InventoryDAL
Testing Our Database Transaction
ADO.NET Part II: The Disconnected Layer
Understanding the Disconnected Layer of ADO.NET
Building a DataSet
Building a DataColumn
Enabling Autoincrementing Fields
Adding DataColumn Objects to a DataTable
Inserting DataTables into DataSets
Processing DataTable Data Using DataTableReader Objects
Serializing DataTable/DataSet Objects As XML
Serializing DataTable/DataSet Objects in a Binary Format
Hydrating a DataTable from a Generic List
Programmatically Deleting Rows
Selecting Rows Based on Filter Criteria
Updating Rows
Working with the DataView Type
A Simple Data Adapter Example
Mapping Database Names to Friendly Names
Navigating Multitabled DataSet Objects
Building the Table Relationships
Updating the Database Tables
Programming with the LINQ APIs
The Role of LINQ to ADO.NET
Programming with LINQ to DataSet
Obtaining a LINQ-Compatible DataTable
The Role of the DataRowExtensions.Field
Hydrating New DataTables from LINQ Queries
Programming with LINQ to SQL
Examining the Generated Entity Classes
Defining Relationships Using Entity Classes
The Strongly Typed DataContext
Programming Against the Generated Types
Inserting New Items
Manipulating XML Documents Using LINQ to XML
LINQ to XML As a Better DOM
Generating Documents from LINQ Queries
Navigating an In-Memory Document
Modifying Data in an XML Document
Introducing Windows Communication Foundation
A Potpourri of Distributed Computing APIs
The Role of DCOM
The Role of COM+/Enterprise Services
The Role of MSMQ
The Role of .NET Remoting
The Role of XML Web Services
The Role of WCF
An Overview of WCF Features
An Overview of Service-Oriented Architecture
Tenet
WCF: The Bottom Line
The Basic Composition of a WCF Application
The ABCs of WCF
Understanding WCF Contracts
The [ServiceContract] Attribute
Service Types As Operational Contracts
Hosting the WCF Service
Establishing the ABCs Within an App.config File
Building the WCF Client Application
Using the WCF Service Library Project Template
Enabling MEX
Designing WCF Data Contracts
Implementing the Service Contract
The Role of the *.svc File
Introducing Windows Workflow Foundation
Defining a Business Process
The Role of WF
The Building Blocks of WF
The WF Runtime
The Core Services of WF
Building a Simple Workflow-Enabled Application
Adding a Code Activity
Adding a While Activity
Examining the WF Engine Hosting Code
Adding Custom Startup Parameters
Invoking Web Services Within Workflows
Building the WF Web Service Consumer
Configuring the IfElse Activity
Performing a Credit Check
Desktop User Interfaces
Programming with Windows Forms
Building a Simple Windows Forms Application (IDE-Free)
Populating the Controls Collection
The Role of System.EventArgs and System.EventHandler
home
Info
sitemap



