Tải bản đầy đủ

1058 illustrated c 2012, 4th edition

www.it-ebooks.info


For your convenience Apress has placed some of the front
matter material after the index. Please use the Bookmarks
and Contents at a Glance links to access them.

www.it-ebooks.info


Contents at a Glance
 About the Author............................................................................................... xxvii
 About the Technical Reviewer ......................................................................... xxviii
 Acknowledgments ............................................................................................. xxix
 Introduction ........................................................................................................ xxx
 Chapter 1: C# and the .NET Framework..................................................................1
 Chapter 2: Overview of C# Programming .............................................................15
 Chapter 3: Types, Storage, and Variables.............................................................33
 Chapter 4: Classes: The Basics.............................................................................49
 Chapter 5: Methods ..............................................................................................67
 Chapter 6: More About Classes...........................................................................113

 Chapter 7: Classes and Inheritance ....................................................................159
 Chapter 8: Expressions and Operators ...............................................................201
 Chapter 9: Statements ........................................................................................239
 Chapter 10: Structs.............................................................................................269
 Chapter 11: Enumerations ..................................................................................279
 Chapter 12: Arrays..............................................................................................293
 Chapter 13: Delegates.........................................................................................323
 Chapter 14: Events..............................................................................................347
 Chapter 15: Interfaces ........................................................................................363
 Chapter 16: Conversions.....................................................................................391
 Chapter 17: Generics ..........................................................................................421
 Chapter 18: Enumerators and Iterators ..............................................................461
 Chapter 19: Introduction to LINQ ........................................................................483
iv

www.it-ebooks.info


 Chapter 20: Introduction to Asynchronous Programming..................................541
 Chapter 21: Namespaces and Assemblies..........................................................603
 Chapter 22: Exceptions.......................................................................................631
 Chapter 23: Preprocessor Directives..................................................................651
 Chapter 24: Reflection and Attributes ................................................................663
 Chapter 25: Other Topics ....................................................................................691
 Index ...................................................................................................................719

v

www.it-ebooks.info


Introduction
The purpose of this book is to teach you the syntax and semantics of the C# programming language in as
clear a manner as possible. C# is a wonderful programming language! I love coding in it. I don’t know
how many programming languages I’ve learned over the years, but C# is by far my favorite. I hope that
by using this book, you can gain an appreciation for C#’s beauty and elegance.
Most books teach programming primarily using text. That’s great for novels, but many of the
important concepts of programming languages can best be understood through a combination of
words, figures, and tables.
Many of us think visually, and figures and tables can help clarify and crystallize our


understanding of a concept. In several years of teaching programming languages, I have found that the
pictures I drew on the whiteboards were the things that most quickly helped the students understand
the concepts I was trying to convey. Illustrations alone, however, are not sufficient to explain a
programming language and platform. The goal of this book is to find the best combination of words and
illustrations to give you a thorough understanding of the language, and to allow the book to serve as a
reference resource as well.
This book is written for anyone who wants an introduction to the C# programming language—
from the novice to the seasoned programmer. For those just getting started in programming, I've
included the basics. For seasoned programmers, the content is laid out succinctly, and in a form that
allows you to go directly to the information required without having to wade through oceans of words.
For both sets of programmers, the content itself is presented graphically, in a form that should make the
language easy to learn.
Enjoy!

Audience, Source Code, and Contact Information
This book was written for beginning and intermediate programmers, and programmers coming from
another language such as Visual Basic or Java. I have tried to remain focused on the C# language itself,
and give an in-depth description of the language and all its parts, rather than straying off into coverage
of .NET or programming practices. I wanted to keep this book as succinct as I could while still covering
the language thoroughly—and there are other good books covering these other topics.
You can download the source code for all the example programs from the Apress web site or
from the web site for this book, which is www.illustratedcsharp.com. And although I can’t answer
specific questions about your code, you can contact me with suggestions and feedback about the book at
dansolis@sbcglobal.net.
I hope this book helps making learning C# an enjoyable experience for you! Take care.
Dan Solis

xxx

www.it-ebooks.info


CHAPTER 1

C# and the .NET Framework
 Before .NET
 Enter Microsoft .NET
 Compiling to the Common Intermediate Language
 Compiling to Native Code and Execution
 The Common Language Runtime
 The Common Language Infrastructure
 Review of the Acronyms
 The Evolution of C#

1
www.it-ebooks.info


CHAPTER 1  C# AND THE .NET FRAMEWORK

Before .NET
The C# programming language was designed for developing programs for Microsoft’s .NET Framework.
This chapter gives a brief look at where .NET came from and its basic architecture. To start off, let’s get
the name right: C# is pronounced “see sharp.”1

Windows Programming in the Late 1990s
In the late 1990s, Windows programming using the Microsoft platform had fractured into a number of
branches. Most programmers were using Visual Basic, C, or C++. Some C and C++ programmers were
using the raw Win32 API, but most were using Microsoft Foundation Classes (MFC). Others had moved
to the Component Object Model (COM).
All these technologies had their own problems. The raw Win32 API was not object-oriented, and
using it required a lot more work than MFC. MFC was object-oriented but was inconsistent and getting
old. COM, although conceptually simple, was complex in its actual coding and required lots of ugly,
inelegant plumbing.
Another shortcoming of all these programming technologies was that they were aimed primarily at
developing code for the desktop rather than the Internet. At the time, programming for the Web was an
afterthought and seemed very different from coding for the desktop.

Goals for the Next-Generation Platform Services
What we really needed was a new start—an integrated, object-oriented development framework that
would bring consistency and elegance back to programming. To meet this need, Microsoft set out to
develop a code execution environment and a code development environment that met these goals.
Figure 1-1 lists these goals.

Figure 1-1. Goals for the next-generation platform

Enter Microsoft .NET
In 2002, Microsoft released the first version of the .NET Framework, which promised to address the old
problems and meet the goals for the next-generation systems. The .NET Framework is a much more

1

I was once interviewed for a contract C# position when the Human Resources interviewer asked me
how much experience I’d had programming in “see pound” (instead of “see sharp”)! It took me a
moment to realize what he was talking about.

2
www.it-ebooks.info


CHAPTER 1  C# AND THE .NET FRAMEWORK

consistent and object-oriented environment than either the MFC or COM programming technologies
Some of its features include the following:


Multiple platforms: The system runs on a broad range of computers, from servers
and desktop machines to PDAs and cell phones.



Industry standards: The system uses industry-standard communication protocols,
such as XML, HTTP, SOAP, JSON, and WSDL.



Security: The system can provide a much safer execution environment, even in the
presence of code obtained from suspect sources.

Components of the .NET Framework
The .NET Framework consists of three components, as shown in Figure 1-2. The execution environment
is called the Common Language Runtime (CLR). The CLR manages program execution at run time,
including the following:


Memory management and garbage collection



Code safety verification



Code execution, thread management, and exception handling

The programming tools include everything you need for coding and debugging, including the
following:


The Visual Studio integrated development environment (IDE)



.NET-compliant compilers (e.g., C#, Visual Basic .NET, F#, IronRuby, and
managed C++)



Debuggers



Web development server-side technologies, such as ASP.NET and WCF

The Base Class Library (BCL) is a large class library used by the .NET Framework and available for
you to use in your programs as well.

Figure 1-2. Components of the .NET Framework

3
www.it-ebooks.info


CHAPTER 1  C# AND THE .NET FRAMEWORK

An Improved Programming Environment
The .NET Framework offers programmers considerable improvements over previous Windows
programming environments. The following sections give a brief overview of its features and their benefits.

Object-Oriented Development Environment
The CLR, the BCL, and C# are designed to be thoroughly object-oriented and act as a well-integrated
environment.
The system provides a consistent, object-oriented model of programming for both local programs
and distributed systems. It also provides a software development interface for desktop application
programming, mobile application programming, and web development, consistent across a broad range
of targets, from servers to cell phones.

Automatic Garbage Collection
The CLR has a service called the garbage collector (GC), which automatically manages memory for you.


The GC automatically removes objects from memory that your program will no
longer access.

The GC relieves programmers of tasks they have traditionally had to perform, such as deallocating
memory and hunting for memory leaks. This is a huge improvement, since hunting for memory leaks
can be difficult and time-consuming.

Interoperability
The .NET Framework was designed for interoperability between different .NET languages, the operating
system or Win32 DLLs, and COM.


The .NET language interoperability allows software modules written using
different .NET languages to interact seamlessly.


A program written in one .NET language can use and even inherit from a class
written in another .NET language, as long as certain rules are followed.



Because of its ability to easily integrate modules produced in different
programming languages, the .NET Framework is sometimes described as
language-agnostic.

4
www.it-ebooks.info


CHAPTER 1  C# AND THE .NET FRAMEWORK



The .NET Framework provides a feature called platform invoke (P/Invoke), which
allows code written for .NET to call and use code not written for .NET. It can use
raw C functions imported from standard Win32 DLLs, such as the Windows APIs.



The .NET Framework also allows interoperability with COM. .NET Framework
software components can call COM components, and COM components can call
.NET components as if they were COM components themselves.

No COM Required
The .NET Framework frees the programmer from the COM legacy. If you’re coming from a COM
programming environment you’ll be happy to know that, as a C# programmer, you don’t need to use any
of the following:


The IUnknown interface: In COM, all objects must implement interface IUnknown. In
contrast, all .NET objects derive from a single class called object. Interface
programming is still an important part of .NET, but it’s no longer the central
theme.



Type libraries: In COM, type information is kept in type libraries as .tlb files,
which are separate from the executable code. In .NET, a program’s type
information is kept bundled with the code in the program file.



Manual reference counting: In COM, the programmer had to keep track of the
number of references to an object to make sure it wasn’t deleted at the wrong
time. In .NET, the GC keeps track of references and removes objects only when
appropriate.



HRESULT: COM used the HRESULT data type to return runtime error codes. .NET
doesn’t use HRESULTs. Instead, all unexpected runtime errors produce exceptions.



The registry: COM applications had to be registered in the system registry, which
holds information about the configurations of the operating system and
applications. .NET applications don’t need to use the registry. This simplifies the
installation and removal of programs. (However, there is something similar called
the global assembly cache, which I’ll cover in Chapter 21.)

Although the amount of COM code that’s currently being written is fairly small, there’s still quite a
number of COM components in systems currently being used, and C# programmers sometimes need to
write code that interfaces with those components. C# 4.0 introduced several new features that make that
task easier. These features are covered in Chapter 25.

5
www.it-ebooks.info


CHAPTER 1  C# AND THE .NET FRAMEWORK

Simplified Deployment
Deploying programs written for the .NET Framework can be much easier than it was before, for the
following reasons:


The fact that .NET programs don’t need to be registered with the registry means
that in the simplest case, a program just needs to be copied to the target machine
and it’s ready to run.



.NET offers a feature called side-by-side execution, which allows different versions
of a DLL to exist on the same machine. This means that every executable can have
access to the version of the DLL for which it was built.

Type Safety
The CLR checks and ensures the type safety of parameters and other data objects—even between
components written in different programming languages.

The Base Class Library
The .NET Framework supplies an extensive base class library, called, not surprisingly, the Base Class
Library (BCL). (It’s also sometimes called the Framework Class Library [FCL]). You can use this extensive
set of available code when writing your own programs. Some of the categories are the following:


General base classes: Classes that provide you with an extremely powerful set of
tools for a wide range of programming tasks, such as file manipulation, string
manipulation, security, and encryption



Collection classes: Classes that implement lists, dictionaries, hash tables, and bit
arrays



Threading and synchronization classes: Classes for building multithreaded
programs



XML classes: Classes for creating, reading, and manipulating XML documents

6
www.it-ebooks.info


CHAPTER 1  C# AND THE .NET FRAMEWORK

Compiling to the Common Intermediate Language
The compiler for a .NET language takes a source code file and produces an output file called an
assembly. Figure 1-3 illustrates the process.


An assembly is either an executable or a DLL.



The code in an assembly isn’t native machine code but an intermediate language
called the Common Intermediate Language (CIL).



An assembly, among other things, contains the following items:


The program’s CIL



Metadata about the types used in the program



Metadata about references to other assemblies

Figure 1-3. The compilation process

 Note The acronym for the intermediate language has changed over time, and different references use different
terms. Two other terms for the CIL that you might encounter are Intermediate Language (IL) and Microsoft
Intermediate Language (MSIL). These terms were frequently used during .NET’s initial development and early
documentation, although they’re used much less frequently now.

7
www.it-ebooks.info


CHAPTER 1  C# AND THE .NET FRAMEWORK

Compiling to Native Code and Execution
The program’s CIL isn’t compiled to native machine code until it’s called to run. At run time, the CLR
performs the following steps, as shown in Figure 1-4:


It checks the assembly’s security characteristics.



It allocates space in memory.



It sends the assembly’s executable code to the just-in-time (JIT) compiler, which
compiles portions of it to native code.

The executable code in the assembly is compiled by the JIT compiler only as it’s needed. It’s then
cached, in case it’s needed for execution again later in the program. Using this process means that code
that isn’t called during execution isn’t compiled to native code, and code that is called need only be
compiled once.

Figure 1-4. Compilation to native code occurs at run time.
Once the CIL is compiled to native code, the CLR manages it as it runs, performing such tasks as
releasing orphaned memory, checking array bounds, checking parameter types, and managing
exceptions. This brings up two important terms:


Managed code: Code written for the .NET Framework is called managed code and
needs the CLR.



Unmanaged code: Code that doesn’t run under the control of the CLR, such as
Win32 C and C++ DLLs, is called unmanaged code.

Microsoft also supplies a tool called the Native Image Generator, or Ngen, which takes an assembly
and produces native code for the current processor. Code that’s been run through Ngen avoids the JIT
compilation process at run time.

8
www.it-ebooks.info


CHAPTER 1  C# AND THE .NET FRAMEWORK

Overview of Compilation and Execution
The same compilation and execution process is followed regardless of the language of the original
source files. Figure 1-5 illustrates the entire compilation and runtime processes for three programs
written in different languages.

Figure 1-5. Overview of the compile-time and runtime processes

9
www.it-ebooks.info


CHAPTER 1  C# AND THE .NET FRAMEWORK

The Common Language Runtime
The core component of the .NET Framework is the CLR, which sits on top of the operating system and
manages program execution, as shown in Figure 1-6. The CLR also provides the following services:


Automatic garbage collection



Security and authentication



Extensive programming functionality through access to the BCL—including
functionality such as web services and data services

Figure 1-6. Overview of the CLR

10
www.it-ebooks.info


CHAPTER 1  C# AND THE .NET FRAMEWORK

The Common Language Infrastructure
Every programming language has a set of intrinsic types representing such objects as integers, floatingpoint numbers, characters, and so on. Historically, the characteristics of these types have varied from
one programming language to another and from platform to platform. For example, the number of bits
constituting an integer has varied widely depending on the language and platform.
This lack of uniformity, however, makes it difficult if we want programs to play well with other
programs and libraries written in different languages. To have order and cooperation, there must be a
set of standards.
The Common Language Infrastructure (CLI) is a set of standards that ties all the components of the
.NET Framework into a cohesive, consistent system. It lays out the concepts and architecture of the
system and specifies the rules and conventions to which all the software must adhere. Figure 1-7 shows
the components of the CLI.

Figure 1-7. Components of the CLI
Both the CLI and C# have been approved as open international standard specifications by Ecma
International. (The name “Ecma” used to be an acronym for the European Computer Manufacturers
Association, but it’s now just a word in itself.) Ecma members include Microsoft, IBM, Hewlett-Packard,
Adobe, and many other corporations associated with computers and consumer electronics.

11
www.it-ebooks.info


CHAPTER 1  C# AND THE .NET FRAMEWORK

Important Parts of the CLI
Although most programmers don’t need to know the details of the CLI specifications, you should at least
be familiar with the meaning and purpose of the Common Type System (CTS) and the Common
Language Specification (CLS).

The Common Type System
The CTS defines the characteristics of the types that must be used in managed code. Some important
aspects of the CTS are the following:


The CTS defines a rich set of intrinsic types, with fixed, specific characteristics for
each type.



The types provided by a .NET-compliant programming language generally map to
some specific subset of this defined set of intrinsic types.



One of the most important characteristics of the CTS is that all types are derived
from a common base class—called object.



Using the CTS ensures that the system types and types defined by the user can be
used by any .NET-compliant language.

The Common Language Specification
The CLS specifies the rules, properties, and behaviors of a .NET-compliant programming language.
The topics include data types, class construction, and parameter passing.

12
www.it-ebooks.info


CHAPTER 1  C# AND THE .NET FRAMEWORK

Review of the Acronyms
This chapter has covered a lot of .NET acronyms, so Figure 1-8 will help you keep them straight.

Figure 1-8. The .NET acronyms

13
www.it-ebooks.info


CHAPTER 1  C# AND THE .NET FRAMEWORK

The Evolution of C#
The current version of the language is version 5.0. Each new release of the language has had a specific
focus for the new features added. The focus of the new features in version 5.0 is asynchronous
programming. I’ll cover these features extensively in Chapter 20.
Figure 1-9 shows the main feature focus for each of the releases of the language and the chapter in
which that material is covered.

Figure 1-9. The focuses of the feature sets for the releases of C#

14
www.it-ebooks.info


CHAPTER 2

Overview of C# Programming
 A Simple C# Program
 Identifiers
 Keywords
 Main: The Starting Point of a Program
 Whitespace
 Statements
 Text Output from a Program
 Comments: Annotating the Code

15
www.it-ebooks.info


CHAPTER 2  OVERVIEW OF C# PROGRAMMING

A Simple C# Program
This chapter lays the groundwork for studying C#. Since I’ll use code samples extensively throughout the
text, I first need to show you what a C# program looks like and what its various parts mean.
I’ll start by demonstrating a simple program and explaining its components one by one. This will
introduce a range of topics, from the structure of a C# program to the method of producing program
output to the screen.
With these source code preliminaries out of the way, I can then use code samples freely throughout
the rest of the text. So, unlike the following chapters, where one or two topics are covered in detail, this
chapter touches on many topics with only a minimum of explanation.
Let’s start by looking at a simple C# program. The complete source code of the program is shown in
the shaded area at the top left of Figure 2-1. As shown, the code is contained in a text file called
SimpleProgram.cs. As you read through it, don’t worry about understanding all the details. Table 2-1
gives a line-by-line description of the code. The shaded area at the bottom left of the figure shows the
output of the program. The right-hand part of the figure is a graphical depiction of the parts of the
program.


When the code is compiled and executed, it displays the string “Hi there!” in a
window on the screen.



Line 5 contains two contiguous slash characters. These characters—and
everything following them on the line—are ignored by the compiler. This is called
a single-line comment.

Figure 2-1. The SimpleProgram program

16
www.it-ebooks.info

4


CHAPTER 2  OVERVIEW OF C# PROGRAMMING

Table 2-1. The SimpleProgram Program, Line by Line

Line Number

Description

Line 1

Tells the compiler that this program uses types from the System namespace.

Line 3

Declares a new namespace, called Simple.

Line 5



The new namespace starts at the open curly brace on line 4
and extends through the matching curly brace on line 12.



Any types declared within this section are members of the
namespace.

Declares a new class type, called Program.


Line 7

Line 9

Any members declared between the matching curly braces
on lines 6 and 11 are members that make up this class.

Declares a method called Main as a member of class Program.


In this program, Main is the only member of the Program
class.



Main is a special function used by the compiler as the
starting point of the program.

Contains only a single, simple statement; this line constitutes the body of Main.


Simple statements are terminated by a semicolon.



This statement uses a class called Console, in namespace
System, to print out the message to a window on the screen



Without the using statement in line 1, the compiler
wouldn’t have known where to look for class Console.

More About SimpleProgram
A C# program consists of one or more type declarations. Much of this book is spent explaining the
different types that you can create and use in your programs. The types in a program can be declared in
any order. In the SimpleProgram example, only a class type is declared.
A namespace is a set of type declarations associated with a name. SimpleProgram uses two
namespaces. It creates a new namespace called Simple, in which it declares its type (class Program), and
uses the Console class defined in a namespace called System.
To compile the program, you can use Visual Studio or the command-line compiler. To use the
command-line compiler, in its simplest form, use the following command in a command window:
csc SimpleProgram.cs

17
www.it-ebooks.info


CHAPTER 2  OVERVIEW OF C# PROGRAMMING

In this command, csc is the name of the command-line compiler, and SimpleProgram.cs is the name
of the source file. CSC stands for “C-Sharp Compiler.”

Identifiers
Identifiers are character strings used to name things such as variables, methods, parameters, and a host
of other programming constructs that will be covered later.
You can create self-documenting identifiers by concatenating meaningful words into a single
descriptive name, using uppercase and lowercase letters (e.g., CardDeck, PlayersHand, FirstName,
SocialSecurityNum). Certain characters are allowed or disallowed at certain positions in an identifier.
Figure 2-2 illustrates these rules.


The alphabetic and underscore characters (a through z, A through Z, and _) are
allowed at any position.



Digits are not allowed in the first position but are allowed everywhere else.



The @ character is allowed in the first position of an identifier but not at any other
position. Although allowed, its use is generally discouraged.

Figure 2-2. Characters allowed in identifiers
Identifiers are case-sensitive. For instance, the variable names myVar and MyVar are different
identifiers.
As an example, in the following code snippet, the variable declarations are all valid and declare
different integer variables. But using such similar names will make coding more error-prone and
debugging more difficult. Those debugging your code at some later time will not be pleased.
// Valid syntactically, but very confusing!
int totalCycleCount;
int TotalCycleCount;
int TotalcycleCount;
I’ll describe the recommended C# naming conventions in Chapter 7.

18
www.it-ebooks.info


CHAPTER 2  OVERVIEW OF C# PROGRAMMING

Keywords
Keywords are the character string tokens used to define the C# language. Table 2-2 gives a complete list
of the C# keywords.
Some important things to know about keywords are the following:


Keywords cannot be used as variable names or any other form of identifier, unless
prefaced with the @ character.



All C# keywords consist entirely of lowercase letters. (.NET type names, however,
use Pascal casing.)

Table 2-2. The C# Keywords
abstract

const

extern

int

out

short

typeof

as

continue

false

interface

override

sizeof

uint

base

decimal

finally

internal

params

stackalloc

ulong

bool

default

fixed

is

private

static

unchecked

break

delegate

float

lock

protected

string

unsafe

byte

do

for

long

public

struct

ushort

case

double

foreach

namespace

readonly

switch

using

catch

else

goto

new

ref

this

virtual

char

enum

if

null

return

throw

void

checked

event

implicit

object

sbyte

true

volatile

class

explicit

in

operator

sealed

try

while

Contextual keywords are identifiers that act as keywords only in certain language constructs. In
those positions, they have particular meanings; but unlike keywords, which cannot ever be used as
identifiers, contextual keywords can be used as identifiers in other parts of the code. Table 2-3 contains
the list of contextual keywords.
Table 2-3. The C# Contextual Keywords
add

ascending

async

await

by

descending

dynamic

equals

from

get

global

group

in

into

join

let

on

orderby

partial

remove

select

set

value

var

where

yield

19
www.it-ebooks.info


CHAPTER 2  OVERVIEW OF C# PROGRAMMING

Main: The Starting Point of a Program
Every C# program must have one class with a method called Main. In the SimpleProgram program shown
previously, it was declared in a class called Program.


The starting point of execution of every C# program is at the first instruction in
Main.



The name Main must be capitalized.

The simplest form of Main is the following:
static void Main( )
{
Statements
}

Whitespace
Whitespace in a program refers to characters that do not have a visible output character. Whitespace in
source code is ignored by the compiler, but is used by the programmer to make the code clearer and
easier to read. Some of the whitespace characters include the following:


Space



Tab



New line



Carriage return

For example, the following code fragments are treated exactly the same by the compiler in spite of
their differences in appearance.
// Nicely formatted
Main()
{
Console.WriteLine("Hi, there!");
}
// Just concatenated
Main(){Console.WriteLine("Hi, there!");}

20
www.it-ebooks.info


Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay

×