Tải bản đầy đủ (.pdf) (857 trang)

programming c 4.0 6th edition

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (6.87 MB, 857 trang )

www.it-ebooks.info
www.it-ebooks.info
Programming C# 4.0
www.it-ebooks.info
www.it-ebooks.info
SIXTH EDITION
Programming C# 4.0
Ian Griffiths, Matthew Adams, and Jesse Liberty
Beijing

Cambridge

Farnham

Köln

Sebastopol

Taipei

Tokyo
www.it-ebooks.info
Programming C# 4.0, Sixth Edition
by Ian Griffiths, Matthew Adams, and Jesse Liberty
Copyright © 2010 Ian Griffiths and Matthew Adams. All rights reserved.
Printed in the United States of America.
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.
O’Reilly
books
may
be purchased for educational, business, or sales promotional use. Online editions


are also available for most titles (
). For more information, contact our
corporate/institutional sales department: 800-998-9938 or

Editors: Mike Hendrickson and Laurel Ruma
Production Editor: Adam Zaremba
Copyeditor: Audrey Doyle
Proofreader: Stacie Arellano
Indexer: Jay Marchand
Cover Designer: Karen Montgomery
Interior Designer: David Futato
Illustrator: Robert Romano
Printing History:
July 2001:
First Edition.
February 2002: Second Edition.
May 2003: Third Edition.
February 2005: Fourth Edition.
December 2007: Fifth Edition.
August 2010: Sixth Edition.
Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of
O’Reilly Media, Inc. Programming C# 4.0, the image of an African crowned crane, and related trade
dress are trademarks of O’Reilly Media, Inc.
Many of the designations used by manufacturers and sellers to distinguish their products are claimed as
trademarks. Where those designations appear in this book, and O’Reilly Media, Inc. was aware of a
trademark claim, the designations have been printed in caps or initial caps.
While every precaution has been taken in the preparation of this book, the publisher and authors assume
no responsibility for errors or omissions, or for damages resulting from the use of the information con-
tained herein.
ISBN: 978-0-596-15983-2

[M]
1280338225
www.it-ebooks.info
Table of Contents
Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xv
1. Introducing C# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Why C#? Why .NET? 1
The .NET Framework Class Library 2
Language Style 3
Composability 4
Managed Code 5
Continuity and the Windows Ecosystem 6
C# 4.0, .NET 4, and Visual Studio 2010 7
Summary 9
2. Basic Programming Techniques . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Getting Started 11
Namespaces and Types 14
Projects and Solutions 19
Comments, Regions, and Readability 24
Bad Comments 26
XML Documentation Comments 26
Variables 28
Variable Types 28
Expressions and Statements 35
Assignment Statements 38
Increment and Decrement Operators 38
Flow Control with Selection Statements 39
if Statements 40
switch and case Statements 45
Iteration Statements 47

foreach Statements 48
for Statements 50
while and do Statements 52
v
www.it-ebooks.info
Breaking Out of a Loop 53
Methods 55
Summary 58
3. Abstracting Ideas with Classes and Structs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
Divide and Conquer 59
Abstracting Ideas with Methods 59
Abstracting Ideas with Objects and Classes 62
Defining Classes 64
Representing State with Properties 64
Protection Levels 66
Initializing with a Constructor 68
Fields: A Place to Put Data 72
Fields Can Be Fickle, but const Is Forever 75
Read-only Fields and Properties 76
Related Constants with enum 79
Value Types and Reference Types 82
Too Many Constructors, Mr. Mozart 88
Overloading 88
Overloaded Methods and Default Named Parameters 89
Object Initializers 92
Defining Methods 95
Declaring Static Methods 98
Static Fields and Properties 99
Static Constructors 101
Summary 102

4. Extensibility and Polymorphism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
Association Through Composition and Aggregation 104
Inheritance and Polymorphism 106
Replacing Methods in Derived Classes 109
Hiding Base Members with new 109
Replacing Methods with virtual and override 112
Inheritance and Protection 114
Calling Base Class Methods 116
Thus Far and No Farther: sealed 118
Requiring Overrides with abstract 121
All Types Are Derived from Object 127
Boxing and Unboxing Value Types 127
C# Does Not Support Multiple Inheritance of Implementation 132
C# Supports Multiple Inheritance of Interface 132
Deriving Interfaces from Other Interfaces 135
Explicit Interface Implementation 136
vi | Table of Contents
www.it-ebooks.info
The Last Resort: Checking Types at Runtime 141
Summary 142
5. Composability and Extensibility with Delegates . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
Functional Composition with delegate 150
Generic Actions with Action<T> 156
Generic Predicates with Predicate<T> 160
Using Anonymous Methods 162
Creating Delegates with Lambda Expressions 163
Delegates in Properties 165
Generic Delegates for Functions 167
Notifying Clients with Events 171
Exposing Large Numbers of Events 180

Summary 183
6. Dealing with Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
When and How to Fail 191
Returning Error Values 194
Debugging with Return Values 200
Exceptions 201
Handling Exceptions 207
When Do finally Blocks Run? 214
Deciding What to Catch 215
Custom Exceptions 218
Summary 220
7. Arrays and Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
Arrays 221
Construction and Initialization 222
Custom Types in Arrays 225
Array Members 230
Array Size 236
List<T> 243
Custom Indexers 247
Finding and Sorting 253
Collections and Polymorphism 254
Creating Your Own IEnumerable<T> 258
Summary 264
8. LINQ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265
Query Expressions 265
Query Expressions Versus Method Calls 267
Extension Methods and LINQ 268
Table of Contents | vii
www.it-ebooks.info
let Clauses 271

LINQ Concepts and Techniques 271
Delegates and Lambdas 271
Functional Style and Composition 273
Deferred Execution 274
LINQ Operators 275
Filtering 275
Ordering 276
Concatenation 279
Grouping 280
Projections 282
Zipping 288
Getting Selective 289
Testing the Whole Collection 291
Aggregation 292
Set Operations 294
Joining 295
Conversions 296
Summary 297
9. Collection Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299
Dictionaries 299
Common Dictionary Uses 301
IDictionary<TKey, TValue> 308
Dictionaries and LINQ 309
HashSet and SortedSet 310
Queues 311
Linked Lists 312
Stacks 313
Summary 314
10. Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315
What Is a String? 316

The String and Char Types 317
Literal Strings and Chars 318
Escaping Special Characters 319
Formatting Data for Output 322
Standard Numeric Format Strings 323
Custom Numeric Format Strings 329
Dates and Times 332
Going the Other Way: Converting Strings to Other Types 336
Composite Formatting with String.Format 337
Culture Sensitivity 338
viii | Table of Contents
www.it-ebooks.info
Exploring Formatting Rules 340
Accessing Characters by Index 341
Strings Are Immutable 341
Getting a Range of Characters 343
Composing Strings 344
Splitting It Up Again 346
Upper- and Lowercase 347
Manipulating Text 348
Mutable Strings with StringBuilder 349
Finding and Replacing Content 353
All Sorts of “Empty” Strings 355
Trimming Whitespace 357
Checking Character Types 360
Encoding Characters 360
Why Encodings Matter 362
Encoding and Decoding 363
Why Represent Strings As Byte Sequences? 370
Summary 370

11. Files and Streams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 371
Inspecting Directories and Files 371
Examining Directories 374
Manipulating File Paths 375
Path and the Current Working Directory 376
Examining File Information 377
Creating Temporary Files 381
Deleting Files 381
Well-Known Folders 383
Concatenating Path Elements Safely 387
Creating and Securing Directory Hierarchies 388
Deleting a Directory 394
Writing Text Files 396
Writing a Whole Text File at Once 396
Writing Text with a StreamWriter 397
When Files Go Bad: Dealing with Exceptions 400
Finding and Modifying Permissions 404
Reading Files into Memory 409
Streams 413
Moving Around in a Stream 419
Writing Data with Streams 421
Reading, Writing, and Locking Files 422
FileStream Constructors 423
Stream Buffers 423
Table of Contents | ix
www.it-ebooks.info
Setting Permissions During Construction 424
Setting Advanced Options 425
Asynchronous File Operations 425
Isolated Storage 428

Stores 429
Reading and Writing Text 430
Defining “Isolated” 431
Managing User Storage with Quotas 436
Managing Isolated Storage 436
Streams That Aren’t Files 439
An Adapting Stream: CryptoStream 443
In Memory Alone: The MemoryStream 444
Representing Binary As Text with Base64 Encoding 444
Summary 447
12. XML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 449
XML Basics (A Quick Review) 449
Elements 450
XHTML 451
X Stands for eXtensible 452
Creating XML Documents 452
XML Elements 455
XML Attributes 456
Putting the LINQ in LINQ to XML 459
Searching in XML with LINQ 461
Searching for a Single Node 465
Search Axes 466
Where Clauses 466
XML Serialization 467
Customizing XML Serialization Using Attributes 469
Summary 471
13. Networking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 473
Choosing a Networking Technology 473
Web Application with Client-Side Code 474
.NET Client and .NET Server 477

.NET Client and External Party Web Service 479
External Client and .NET Web Service 480
WCF 481
Creating a WCF Project 481
WCF Contracts 482
WCF Test Client and Host 483
Hosting a WCF Service 486
x | Table of Contents
www.it-ebooks.info
Writing a WCF Client 493
Bidirectional Communication with Duplex Contracts 501
HTTP 511
WebClient 512
WebRequest and WebResponse 516
Sockets 522
IP, IPv6, and TCP 523
Connecting to Services with the Socket Class 528
Implementing Services with the Socket Class 531
Other Networking Features 536
Summary 537
14. Databases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 539
The .NET Data Access Landscape 539
Classic ADO.NET 540
LINQ and Databases 544
Non-Microsoft Data Access Technologies 545
WCF Data Services 546
Silverlight and Data Access 546
Databases 547
The Entity Data Model 548
Generated Code 551

Changing the Mapping 554
Relationships 555
Inheritance 562
Queries 563
LINQ to Entities 563
Entity SQL 568
Mixing ESQL and LINQ 570
The EntityClient ADO.NET Provider 571
Object Context 571
Connection Handling 571
Creating, Updating, and Deleting 574
Transactions 576
Optimistic Concurrency 581
Context and Entity Lifetime 583
WCF Data Services 584
Summary 588
15. Assemblies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 589
.NET Components: Assemblies 589
References 590
Writing Libraries 593
Table of Contents | xi
www.it-ebooks.info
Protection 595
Naming 598
Signing and Strong Names 599
Loading 601
Loading from the Application Folder 602
Loading from the GAC 603
Loading from a Silverlight .xap File 603
Explicit Loading 604

Summary 605
16. Threads and Asynchronous Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 607
Threads 609
Threads and the OS Scheduler 611
The Stack 613
The Thread Pool 620
Thread Affinity and Context 622
Common Thread Misconceptions 623
Multithreaded Coding Is Hard 629
Multithreading Survival Strategies 632
Synchronization Primitives 634
Monitor 634
Other Lock Types 645
Other Coordination Mechanisms 649
Events 649
Countdown 650
BlockingCollection 650
Asynchronous Programming 651
The Asynchronous Programming Model 652
The Event-Based Asynchronous Pattern 655
Ad Hoc Asynchrony 656
The Task Parallel Library 656
Tasks 657
Cancellation 663
Error Handling 665
Data Parallelism 666
Parallel For and ForEach 667
PLINQ: Parallel LINQ 669
Summary 670
17. Attributes and Reflection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 671

Attributes 671
Types of Attributes 672
Custom Attributes 673
xii | Table of Contents
www.it-ebooks.info
Reflection 677
Inspecting Metadata 678
Type Discovery 679
Reflecting on a Specific Type 681
Late Binding 683
Summary 686
18. Dynamic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 687
Static Versus Dynamic 687
The Dynamic Style and COM Automation 689
The dynamic Type 690
Object Types and dynamic 693
dynamic in Noninterop Scenarios? 703
Summary 706
19. Interop with COM and Win32 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 707
Importing ActiveX Controls 707
Importing a Control in .NET 708
Interop Assemblies 711
No PIA 712
64-bit Versus 32-bit 713
P/Invoke 716
Pointers 720
C# 4.0 Interop Syntax Enhancements 725
Indexed Properties 725
Optional ref 726
Summary 727

20. WPF and Silverlight . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 729
Xaml and Code Behind 731
Xaml and Objects 735
Elements and Controls 738
Layout Panels 739
Graphical Elements 748
Controls 755
User Controls 760
Control Templates 761
Styles 764
The Visual State Manager 766
Data Binding 767
Data Templates 769
Summary 773
Table of Contents | xiii
www.it-ebooks.info
21. Programming ASP.NET Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 775
Web Forms Fundamentals 775
Web Forms Events 776
Web Forms Life Cycle 778
Creating a Web Application 779
Code-Behind Files 780
Adding Controls 781
Server Controls 783
Data Binding 784
Examining the Code 789
Adding Controls and Events 790
Summary 794
22. Windows Forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 795
Creating the Application 796

Adding a Binding Source 797
Controls 800
Docking and Anchoring 805
Data Binding 806
Event Handling 811
Summary 813
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 815
xiv | Table of Contents
www.it-ebooks.info
Preface
Microsoft unveiled the .NET Framework in 2000, and in the decade that followed, it
became an extremely popular choice for developing software for Windows.
While .NET supports many programming languages, it is most strongly associated with
the language designed specifically for the platform: C#.
C# has grown considerably since its launch. Each new version enabled new program-
ming techniques—C# 2.0 added generics and enhanced functional programming ca-
pabilities, then integrated query features and yet more powerful functional capabilities
arrived in C# 3.0, and now C# 4.0 adds new dynamic language capabilities.
The .NET Framework has grown with the language. Back in .NET 1.0, the class libraries
offered relatively patchy coverage of the underlying Windows capabilities. Moreover,
the library features that were unique to .NET, rather than being wrappers for something
else, were relatively modest. Now, as well as more comprehensive platform coverage
we have a GUI framework (WPF), much stronger database capabilities, powerful sup-
port for concurrent execution, and an extensive set of communication services (WCF),
to name just a few of the available features. And the features that have been there since
version 1.0, such as web support (ASP.NET), have been fleshed out substantially.
.NET is no longer limited to running just on Windows. Some people recognized its
potential for platform independence early on, but for years, Microsoft supported C#
just on Windows, leaving open source projects to offer the only way to run C# on other
systems. But in 2008, the release of Silverlight 2 saw C# code running with Microsoft’s

full support on non-Windows platforms such as the Mac for the first time.
The C# language has come a long way since 2000, in both reach and size. Our goal
with Programming C# 4.0 is to show how to use C#.
How This Book Is Organized
The book begins by looking at the details of the C# language that you will use in
everyday programming. We then look at the most common parts of the .NET Frame-
work class library that you will also use very regularly. Next, we move into some more
xv
www.it-ebooks.info
specialized areas of the framework. Finally, we look at some of the application frame-
works for building Windows and web applications in .NET.
Chapter 1, Introducing C#
This chapter talks about the nature of C# and its relationship with the .NET
Framework.
Chapter 2, Basic Programming Techniques
In this chapter, we show the core elements of C# code—the steps required to get
up and running, and fundamental features such as variables, flow control, loops,
and methods.
Chapter 3, Abstracting Ideas with Classes and Structs
C# supports object-oriented programming, and this chapter describes the lan-
guage features dedicated to these techniques.
Chapter 4, Extensibility and Polymorphism
This chapter continues the discussion from the preceding chapter, illustrating how
C# supports inheritance, interfaces, and related concepts.
Chapter 5, Composability and Extensibility with Delegates
C# isn’t limited to object-oriented programming—it also supports some very
powerful functional programming idioms. This chapter shows how these can
sometimes be more flexible and also simpler than OO techniques.
Chapter 6, Dealing with Errors
All programs encounter failures, whether due to programming errors, unexpected

input, network failures, or a host of other eventualities. This chapter shows the
options for detecting and responding robustly to errors.
Chapter 7, Arrays and Lists
This chapter shows the tools C# offers for representing simple collections of
information.
Chapter 8, LINQ
It’s not enough merely to be able to represent collections, so this chapter shows
how you can use the integrated query features in C# to process your collections of
data.
Chapter 9, Collection Classes
This chapter shows some of the more specialized classes for working with collec-
tions in particular ways.
Chapter 10, Strings
Text is a particularly important data type for most applications, so this chapter
shows how text is represented, and how you can format data into textual form.
Chapter 11, Files and Streams
This chapter shows how to store information on disk and read it back in, and how
to perform other filesystem operations. It also shows how some of the abstractions
used when working with files can be applied in other scenarios.
xvi | Preface
www.it-ebooks.info
Chapter 12, XML
This chapter shows the classes offered by the .NET Framework for processing
XML, and how these can work in conjunction with the LINQ features in C#.
Chapter 13, Networking
In this chapter, we look at the various techniques for communicating over a
network.
Chapter 14, Databases
This chapter shows how to access a database from C#.
Chapter 15, Assemblies

In this chapter, we show how to compile code into libraries for reuse, and how
programs made up from multiple components work.
Chapter 16, Threads and Asynchronous Code
Many programs need to deal with concurrency, and this chapter shows the tools
and techniques available.
Chapter 17, Attributes and Reflection
C# has the ability to inspect the structure of code, which makes it easier to auto-
mate certain kinds of tasks. This chapter shows the API for doing this, and how
you can extend the structural information through attributes.
Chapter 18, Dynamic
One of the new features in C# 4.0 is support for dynamic binding. This is partic-
ularly useful in certain interop scenarios, as we discuss in this chapter.
Chapter 19, Interop with COM and Win32
Sometimes it’s necessary for C# code to communicate with components not de-
signed to be used from .NET. This chapter shows how to do this with both COM
components and Win32-style DLLs.
Chapter 20, WPF and Silverlight
WPF and Silverlight offer very similar programming models for building user in-
terfaces. This chapter shows how to use that model from C#.
Chapter 21, Programming ASP.NET Applications
This chapter shows how to use ASP.NET, the part of the .NET Framework de-
signed for building web applications.
Chapter 22, Windows Forms
This chapter shows how to use Windows Forms, which is a wrapper around the
classic Windows user interface mechanisms. While it is less flexible than WPF, it
can offer an easier way to integrate with old components such as ActiveX controls.
Where to Find Features New in C# 4.0 and .NET 4
Although this book is written to be read as a whole, we expect that some readers will
want to look for the features new to C# 4.0, and also to .NET 4. Since our goal is to
show how the C# language is used today, we have avoided structuring the book around

Preface | xvii
www.it-ebooks.info
the history of the language, because you will use language features of varying ages in
combination. As it happens, one of the new features in C# 4.0 serves a very specific
purpose, so it gets its own chapter, but for the most part, new language features are
spread throughout the book, because we aim to mention them where you need to know
about them. We cannot point you at a particular set of chapters, so instead, here’s a
quick guide to where we discuss these features.
Chapter 1 talks about the broad goals behind the new features in C# 4.0. Chapter 3
shows the use of default values and named arguments (and these come up again very
briefly in Chapters
11 and 17). Chapter 7 describes variance, a rather technical feature
of the type system that has some useful implications for collection types.
Chapter 16
talks about the extensive new multithreading support added in .NET 4. Chapter 18 is
dedicated entirely to a new language feature: support for dynamic programming.
Chapter 19 describes the new no-PIA feature, and some features that allow more elegant
code in some interop scenarios.
Who This Book Is For
If you have some basic knowledge of C# but want to brush up your skills, or if you are
proficient in another programming language such as C++ or Java, or even if C# is your
first programming language, this book is for you.
What You Need to Use This Book
To make the best use of this book, please obtain the latest release of Visual Studio 2010.
Any edition will do, including the free Express edition for C#, which can be
downloaded from
/>For
Chapter 14 you will need a copy of SQL Server or SQL Server Express. Some editions
of Visual Studio will install SQL Server Express for you by default, so you may already
have this.

The example source code for this book is available through the O’Reilly site at
http://
oreilly.com/catalog/9780596159832/
.
Conventions Used in This Book
The following font conventions are used in this book:
Italic is used for:
• Pathnames, filenames, and program names
• Internet addresses, such as domain names and URLs
• New terms where they are defined
xviii | Preface
www.it-ebooks.info
Constant Width is used for:
• Command lines and options that should be typed verbatim
• Names and keywords in program examples, including method names, variable
names, and class names
Constant Width Italic is used for:
• Replaceable items, such as variables or optional elements, within syntax lines or
code
Constant Width Bold is used for:
• Emphasis within program code
Pay special attention to notes set apart from the text with the following icons:
This is a tip. It contains useful supplementary information about the
topic at hand.
This is a warning. It helps you solve and avoid annoying problems.
Using Code Examples
This book is here to help you get your job done. In general, you may use the code in
this book in your programs and documentation. You do not need to contact us for
permission unless you’re reproducing a significant portion of the code. For example,
writing a program that uses several chunks of code from this book does not require

permission. Selling or distributing a CD-ROM of examples from O’Reilly books does
require permission. Answering a question by citing this book and quoting example
code does not require permission. Incorporating a significant amount of example code
from this book into your product’s documentation does require permission.
We appreciate, but do not require, attribution. An attribution usually includes the title,
author, publisher, and ISBN. For example: "Programming C# 4.0, Sixth Edition, by
Ian Griffiths, Matthew Adams, and Jesse Liberty. Copyright 2010 Ian Griffiths and
Matthew Adams, 978-0-596-15983-2.”
Preface | xix
www.it-ebooks.info
Safari® Books Online
Safari Books Online is an on-demand digital library that lets you easily
search over 7,500 technology and creative reference books and videos to
find the answers you need quickly.
With a subscription, you can read any page and watch any video from our library online.
Read books on your cell phone and mobile devices. Access new titles before they are
available for print, and get exclusive access to manuscripts in development and post
feedback for the authors. Copy and paste code samples, organize your favorites, down-
load chapters, bookmark key sections, create notes, print out pages, and benefit from
tons of other time-saving features.
O’Reilly Media has uploaded this book to the Safari Books Online service. To have full
digital access to this book and others on similar topics from O’Reilly and other pub-
lishers, sign up for free at
/>Acknowledgments
From Ian Griffiths
I want to thank the technical reviewers, whose feedback helped to improve this book:
Nicholas Paldino, Chris Smith, Chris Williams, Michael Eaton, Brian Peek, and
Stephen Toub.
Everyone at O’Reilly has provided a great deal of support and patience throughout the
project, so many thanks to Mike Hendrickson, Laurel Ruma, Audrey Doyle, and Sumita

Mukherji. Thanks also to John Osborn for getting things started in the early days of
this project, and for getting Matthew and me on board as O’Reilly authors in the first
place, all those years ago.
Thank you to my coauthor for not learning his lesson from the last book and agreeing
to write another with me. And finally, thank you to Jesse Liberty for asking us to take
over his book.
From Matthew Adams
I’d like to add my thanks to those of my coauthor to all those at O’Reilly whose patience,
help, and support have made this book possible, and to all our reviewers whose feed-
back has been invaluable.
In addition, I’d like to add a nod to Karolina Lemiesz, coffee wizard at the Starbucks
where most of my text was written, for the constant supply of ristretto, and an education
in coffee tasting when work got too much.
xx | Preface
www.it-ebooks.info
As always, my partner Una provided the necessary foundation of love and support
(despite her own book deadlines). And finally, anyone who tells you that squeezing a
book out of an author is a breeze is clearly deluded, but my coauthor makes it look
easy. My thanks go to him especially for his forbearance, wit, and friendship. And good
dinners.
Preface | xxi
www.it-ebooks.info
www.it-ebooks.info
CHAPTER 1
Introducing C#
C#—pronounced “See Sharp”—is a programming language designed for Micro-
soft’s .NET platform. Since its first release in 2002, C# has found many roles. It is
widely used on the server side of websites, and also on both the client and server in
line-of-business Windows desktop applications. You can write smartphone user inter-
faces and Xbox 360 games in C#. More recently, Microsoft’s Silverlight platform has

made C# an option for writing Rich Internet Applications that run in a web browser.
But what kind of language is C#? To understand a language well enough to use it
effectively, it’s not enough to focus purely on the details and mechanisms, although
we’ll be spending plenty of time on those in this book. It is equally important to un-
derstand the thinking behind the details. So in this chapter, we’ll look at what problems
C# was built to solve. Then we’ll explore the style of the language, through aspects
that distinguish it from other languages. And we’ll finish the chapter with a look at the
latest step in the evolution of C#, its fourth version.
Why C#? Why .NET?
Programming languages exist to help developers be more productive. Many successful
languages simplify or automate tedious tasks that previously had to be done by hand.
Some offer new techniques that allow old problems to be tackled more effectively, or
on a larger scale than before. How much difference C# can make to you will depend
on your programming background, of course, so it’s worth considering what sorts of
people the language designers had in mind when they created C#.
C# is aimed at developers working on the Windows platform, and its syntax is instantly
familiar to users of C or C++, or other languages that draw from the same tradition,
such as JavaScript and Java. Fundamental language elements such as statements, ex-
pressions, function declarations, and flow control are modeled as closely as possible
on their equivalents in C family languages.
1
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
×