in-Chapter 21, Programming ASP.NET Applications This chapter shows how to use ASP.NET, the part of the .NET Framework signed for building web applications.. Chapter 18 isdedicated entire
Trang 3Programming C# 4.0
Trang 5SIXTH EDITION Programming C# 4.0
Ian Griffiths, Matthew Adams, and Jesse Liberty
Beijing • Cambridge • Farnham • Köln • Sebastopol • Taipei • Tokyo
Trang 6Programming 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 (http://my.safaribooksonline.com) For more information, contact our corporate/institutional sales department: 800-998-9938 or corporate@oreilly.com.
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 tained herein.
con-ISBN: 978-0-596-15983-2
[M]
1280338225
Trang 7Table of Contents
Preface xv
1 Introducing C# 1
2 Basic Programming Techniques 11
Trang 8Breaking Out of a Loop 53
3 Abstracting Ideas with Classes and Structs 59
4 Extensibility and Polymorphism 103
Trang 9The Last Resort: Checking Types at Runtime 141
5 Composability and Extensibility with Delegates 143
6 Dealing with Errors 185
7 Arrays and Lists 221
8 LINQ 265
Table of Contents | vii
Trang 10let Clauses 271
Trang 11Exploring Formatting Rules 340
11 Files and Streams 371
Table of Contents | ix
Trang 12Setting Permissions During Construction 424
Trang 1314 Databases 539
Trang 14Protection 595
Trang 1519 Interop with COM and Win32 707
Trang 1621 Programming ASP.NET Applications 775
22 Windows Forms 795
Trang 17Microsoft unveiled the NET Framework in 2000, and in the decade that followed, itbecame an extremely popular choice for developing software for Windows.While NET supports many programming languages, it is most strongly associated withthe language designed specifically for the platform: C#
C# has grown considerably since its launch Each new version enabled new ming techniques—C# 2.0 added generics and enhanced functional programming ca-pabilities, then integrated query features and yet more powerful functional capabilitiesarrived in C# 3.0, and now C# 4.0 adds new dynamic language capabilities
program-The NET Framework has grown with the language Back in NET 1.0, the class librariesoffered relatively patchy coverage of the underlying Windows capabilities Moreover,the library features that were unique to NET, rather than being wrappers for somethingelse, were relatively modest Now, as well as more comprehensive platform coverage
we have a GUI framework (WPF), much stronger database capabilities, powerful port for concurrent execution, and an extensive set of communication services (WCF),
sup-to name just a few of the available features And the features that have been there sinceversion 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 itspotential 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 othersystems But in 2008, the release of Silverlight 2 saw C# code running with Microsoft’sfull 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 ineveryday 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
Trang 18specialized areas of the framework Finally, we look at some of the application works for building Windows and web applications in NET.
frame-Chapter 1, Introducing C#
This chapter talks about the nature of C# and its relationship with the NETFramework
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 guage features dedicated to these techniques
lan-Chapter 4, Extensibility and Polymorphism
This chapter continues the discussion from the preceding chapter, illustrating howC# 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 verypowerful functional programming idioms This chapter shows how these cansometimes be more flexible and also simpler than OO techniques
Chapter 6, Dealing with Errors
All programs encounter failures, whether due to programming errors, unexpectedinput, network failures, or a host of other eventualities This chapter shows theoptions for detecting and responding robustly to errors
Chapter 7, Arrays and Lists
This chapter shows the tools C# offers for representing simple collections ofinformation
Chapter 8, LINQ
It’s not enough merely to be able to represent collections, so this chapter showshow you can use the integrated query features in C# to process your collections ofdata
Chapter 9, Collection Classes
This chapter shows some of the more specialized classes for working with tions in particular ways
collec-Chapter 10, Strings
Text is a particularly important data type for most applications, so this chaptershows 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 abstractionsused when working with files can be applied in other scenarios
Trang 19Chapter 16, Threads and Asynchronous Code
Many programs need to deal with concurrency, and this chapter shows the toolsand techniques available
Chapter 17, Attributes and Reflection
C# has the ability to inspect the structure of code, which makes it easier to mate certain kinds of tasks This chapter shows the API for doing this, and howyou can extend the structural information through attributes
auto-Chapter 18, Dynamic
One of the new features in C# 4.0 is support for dynamic binding This is ularly useful in certain interop scenarios, as we discuss in this chapter
partic-Chapter 19, Interop with COM and Win32
Sometimes it’s necessary for C# code to communicate with components not signed to be used from NET This chapter shows how to do this with both COMcomponents and Win32-style DLLs
de-Chapter 20, WPF and Silverlight
WPF and Silverlight offer very similar programming models for building user terfaces This chapter shows how to use that model from C#
in-Chapter 21, Programming ASP.NET Applications
This chapter shows how to use ASP.NET, the part of the NET Framework signed for building web applications
de-Chapter 22, Windows Forms
This chapter shows how to use Windows Forms, which is a wrapper around theclassic Windows user interface mechanisms While it is less flexible than WPF, itcan 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 willwant to look for the features new to C# 4.0, and also to NET 4 Since our goal is toshow how the C# language is used today, we have avoided structuring the book around
Preface | xvii
Trang 20the history of the language, because you will use language features of varying ages incombination As it happens, one of the new features in C# 4.0 serves a very specificpurpose, so it gets its own chapter, but for the most part, new language features arespread throughout the book, because we aim to mention them where you need to knowabout them We cannot point you at a particular set of chapters, so instead, here’s aquick guide to where we discuss these features.
Chapter 1 talks about the broad goals behind the new features in C# 4.0 Chapter 3shows the use of default values and named arguments (and these come up again verybriefly 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 16talks about the extensive new multithreading support added in NET 4 Chapter 18 isdedicated entirely to a new language feature: support for dynamic programming.Chapter 19 describes the new no-PIA feature, and some features that allow more elegantcode 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 areproficient in another programming language such as C++ or Java, or even if C# is yourfirst 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 bedownloaded from http://www.microsoft.com/express/
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 alreadyhave 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
Trang 21Constant Width is used for:
• Command lines and options that should be typed verbatim
• Names and keywords in program examples, including method names, variablenames, and class names
Constant Width Italic is used for:
• Replaceable items, such as variables or optional elements, within syntax lines orcode
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 inthis book in your programs and documentation You do not need to contact us forpermission 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 examplecode 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 andMatthew Adams, 978-0-596-15983-2.”
Preface | xix
Trang 22Safari® Books Online
Safari Books Online is an on-demand digital library that lets you easilysearch over 7,500 technology and creative reference books and videos tofind 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 areavailable for print, and get exclusive access to manuscripts in development and postfeedback for the authors Copy and paste code samples, organize your favorites, down-load chapters, bookmark key sections, create notes, print out pages, and benefit fromtons of other time-saving features
O’Reilly Media has uploaded this book to the Safari Books Online service To have fulldigital access to this book and others on similar topics from O’Reilly and other pub-lishers, sign up for free at http://my.safaribooksonline.com/?portal=oreilly
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, andStephen Toub
Everyone at O’Reilly has provided a great deal of support and patience throughout theproject, so many thanks to Mike Hendrickson, Laurel Ruma, Audrey Doyle, and SumitaMukherji Thanks also to John Osborn for getting things started in the early days ofthis project, and for getting Matthew and me on board as O’Reilly authors in the firstplace, 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 takeover 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 Starbuckswhere most of my text was written, for the constant supply of ristretto, and an education
in coffee tasting when work got too much
Trang 23As 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 abook out of an author is a breeze is clearly deluded, but my coauthor makes it lookeasy My thanks go to him especially for his forbearance, wit, and friendship And gooddinners.
Preface | xxi
Trang 25CHAPTER 1
Introducing C#
C#—pronounced “See Sharp”—is a programming language designed for soft’s NET platform Since its first release in 2002, C# has found many roles It iswidely used on the server side of websites, and also on both the client and server inline-of-business Windows desktop applications You can write smartphone user inter-faces and Xbox 360 games in C# More recently, Microsoft’s Silverlight platform hasmade 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 iteffectively, it’s not enough to focus purely on the details and mechanisms, althoughwe’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 problemsC# was built to solve Then we’ll explore the style of the language, through aspectsthat distinguish it from other languages And we’ll finish the chapter with a look at thelatest step in the evolution of C#, its fourth version
Micro-Why C#? Micro-Why NET?
Programming languages exist to help developers be more productive Many successfullanguages 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 ofpeople the language designers had in mind when they created C#
C# is aimed at developers working on the Windows platform, and its syntax is instantlyfamiliar 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
Trang 26A familiar syntax is not enough of a reason to pick a language, of course, so C# offersproductivity-enhancing features not found in some of its predecessors Garbage col-lection frees developers from the tyranny of common memory management problemssuch as memory leaks and circular references Verifiable type safety of compiled coderules out a wide range of bugs and potential security flaws While C or C++ Windowsdevelopers may not be accustomed to those features, they will seem old hat to Javaveterans, but Java has nothing to compete with the “LINQ” features C# offers forworking with collections of information, whether in object models, XML documents,
or databases Integrating code from external components is remarkably painless, eventhose written in other languages C# also incorporates support for functional pro-gramming, a powerful feature previously most commonly seen in academic languages.Many of the most useful features available to C# developers come from the NETFramework, which provides the runtime environment and libraries for C#, and allother NET languages, such as VB.NET C# was designed for NET, and one of themain benefits of its close relationship with the NET Framework is that working withframework features such as the class library feels very natural
The NET Framework Class Library
Working in C# means more than using just the language—the classes offered bythe NET Framework are an extremely important part of the C# developer’s everydayexperience (and they account for a lot of this book’s content) Most of the library func-tionality falls into one of three categories: utility features written in NET, wrappersaround Windows functionality, and frameworks
The first group comprises utility types such as dictionaries, lists, and other collectionclasses, as well as string manipulation facilities such as a regular expression engine.There are also features that operate on a slightly larger scale, such as the object modelsfor representing XML documents
Some library features are wrappers around underlying OS functionality For example,there are classes for accessing the filesystem, and for using network features such assockets And there are classes for writing output to the console, which we can illustratewith the obligatory first example of any programming language book, shown inExample 1-1
Example 1-1 The inevitable “Hello, world” example
Trang 27We’ll examine all the pieces shown here in due course, but for now, note that even thissimplest of examples depends on a class from the library—the System.Console class inthis case—to do its job.
Finally, the class library offers whole frameworks to support building certain kinds ofapplications For example, Windows Presentation Foundation (WPF) is a frameworkfor building Windows desktop software; ASP.NET (which is not an acronym, despiteappearances) is a framework for building web applications Not all frameworks areabout user interfaces—Windows Communication Foundation (WCF) is designed forbuilding services accessed over the network by other computer systems, for instance.These three categories are not strict, as quite a few classes fit into two For example,the parts of the class library that provide access to the filesystem are not just thin wrap-pers around existing Win32 APIs They add new object-oriented abstractions, provid-ing significant functionality beyond the basic file I/O services, so these types fit intoboth the first and second categories Likewise, frameworks usually need to integratewith underlying services to some extent—for example, although the Windows Forms
UI framework has a distinctive API of its own, a lot of the underlying functionality isprovided by Win32 components So the three categories here are not strict They justoffer a useful idea of what sorts of things you can find in the class libraries
Language Style
C# is not the only language that runs on the NET Framework Indeed, support formultiple languages has always been a key feature of NET, reflected in the name of its
runtime engine, the CLR or Common Language Runtime As this name implies, NET
is not just for one language—numerous languages have access to the services ofthe NET Framework class library Why might you choose C# over the others?
We already mentioned one important reason: C# was designed specifically for NET
If you are working with NET technologies such as WPF or ASP.NET, you’ll be speakingtheir language if you work in C# Compare this with C++, which supports NETthrough extensions to the original language The extensions are carefully thought outand work well, but code that uses NET libraries just looks different from normalC++, so programs that bridge the worlds of NET and standard C++ never feel com-pletely coherent And the dual personality often presents dilemmas—should you usestandard C++ collection classes or the ones in the NET class library, for example? Innative NET languages such as C#, such questions do not emerge
But C# is not unique in this respect Visual Studio 2010 ships with three languagesdesigned for NET: C#, VB.NET, and F# (Although VB.NET follows on from itsnon-.NET Visual Basic predecessors, it was radically different in some important ways
It is a native NET language with a VB-like syntax rather than VB 6 with NET bilities bolted on.) The choice between these languages comes down to what style oflanguage you prefer
capa-Language Style | 3
Trang 28F# is the odd one out here It’s a functional programming language, heavily influenced
by a language called ML Back in 1991, when your authors were first-year students, ouruniversity’s computer science course chose ML for the first programming languagelectures in part because it was so academic that none of the students would previouslyhave come across anything like it F# is still at the academic end of the spectrum despitehaving climbed far enough down the ivory tower to be a standard part of a mainstreamdevelopment environment It excels at complicated calculations and algorithms, andhas some characteristics that can help with parallel execution However, as with manyfunctional languages, the cost of making some hard problems easier is that a lot ofthings that are easy in more traditional languages are remarkably hard in F#—functional languages are adept at complex problems, but can be clumsy with simpleones It seems likely that F# will mostly be used in scientific or financial applicationswhere the complexity of the computation to be performed dwarfs the complexity ofthe code that needs to act on the results of those calculations
While F# feels distinctly other, VB.NET and C# have a lot of similarities The most
obvious factor in choosing between these is that VB.NET is easier to learn for someonefamiliar with Visual Basic syntax, while C# will be easier for someone familiar with aC-like language However, there is a subtler difference in language philosophy that goesbeyond the syntax
Composability
A consistent theme in the design of the C# programming language is that its creatorstend to prefer general-purpose features over specialized ones The most obvious ex-
ample of this is LINQ, the Language INtegrated Query feature added in C# 3.0
Su-perficially, this appears to add SQL-like query features to the language, providing anatural way to integrate database access into your code Example 1-2 shows a simplequery
Example 1-2 Data access with LINQ
var californianAuthors = from author in pubs.authors
where author.state == "CA"
Trang 29with object models Moreover, many of the individual features can be used in othercontexts, as we’ll see in later chapters C# prefers small, composable, general-purposefeatures over monolithic, specialized ones.
A striking example of this philosophy is a feature that was demonstrated in prototypeform in C#, but which eventually got left out: XML literals This experimental syntaxallowed inline XML, which compiled into code that built an object model representingthat XML The C# team’s decision to omit this feature illustrates a stylistic preferencefor generality over highly specialized features—while the LINQ syntax has many ap-plications, XML literal syntax cannot be used for anything other than XML, and thisdegree of specialization would feel out of place in C#.*
Managed Code
The NET Framework provides more than just a class library It also provides services
in subtler ways that are not accessed explicitly through library calls For example, earlier
we mentioned that C# can automate some aspects of memory management, a ous source of bugs in C++ code Abandoning heap-allocated objects once you’re donewith them is a coding error in C++, but it’s the normal way to free them in NET Thisservice is provided by the CLR—the NET Framework’s runtime environment Al-though the C# compiler works closely with the runtime to make this possible, provid-ing the necessary information about how your code uses objects and data, it’s ultimatelythe runtime that does the work of garbage collection
notori-Depending on what sorts of languages you may have worked with before, the idea thatthe language depends heavily on the runtime might seem either completely natural orsomewhat disconcerting It’s certainly different from how C and C++ work—withthose languages, the compiler’s output can be executed directly by the computer, andalthough those languages have some runtime services, it’s possible to write code thatcan run without them But C# code cannot even execute without the help of the run-
time Code that depends entirely on the runtime is called managed code.
Managed compilers do not produce raw executable code Instead, they produce anintermediate form of code called IL, the Intermediate Language.† The runtime decidesexactly how to convert it into something executable One practical upshot of managedcode is that a compiled C# program can run on both 32-bit and 64-bit systems withoutmodification, and can even run on different processor architectures—it’s often possible
* VB.NET supports XML literals Since C# 2.0 shipped, the C# and VB.NET teams have operated a policy of keeping the feature sets of the two languages similar, so the fact that VB.NET picked up a feature that C# abandoned shows a clear difference in language philosophy.
† Depending on whether you read Microsoft’s documentation, or the ECMA CLI (Common Language Infrastructure) specifications that define the standardized parts of NET and C#, IL’s proper name is either MSIL (Microsoft IL) or CIL (Common IL), respectively The unofficial name, IL, seems more popular in practice.
Language Style | 5
Trang 30for code that runs on an ARM-based handheld device to run unmodified on Intel-basedPCs, or on the PowerPC architecture found in the Xbox 360 game console.
As interesting as CPU independence may be, in practice the most useful aspect of aged code and IL is that the NET runtime can provide useful services that are very hardfor traditional compilation systems to implement well In other words, the point is tomake developers more productive The memory management mentioned earlier is justone example Others include a security model that takes the origin of code into accountrather than merely the identity of the user who happens to be running the code; flexiblemechanisms for loading shared components with robust support for servicing and ver-sioning; runtime code optimization based on how the code is being used in practicerather than how the compiler guesses it might be used; and as already mentioned, theCLR’s ability to verify that code conforms to type safety rules before executing it, rulingout whole classes of security and stability bugs
man-If you’re a Java developer, all of this will sound rather familiar—just substitute
byte-code for IL and the story is very similar Indeed, a popular but somewhat ignorant “joke”
among the less thoughtful members of the Java community is to describe C# as a poorimitation of Java When the first version of C# appeared, the differences were subtle,but the fact that Java went on to copy several features from C# illustrates that C# wasalways more than a mere clone The languages have grown more obviously differentwith each new version, but one difference, present from the start, is particularly im-portant for Windows developers: C# has always made it easy to get at the features ofthe underlying Windows platform
Continuity and the Windows Ecosystem
Software development platforms do not succeed purely on their own merits—contextmatters For example, widespread availability of third-party components and tools canmake a platform significantly more compelling Windows is perhaps the most strikingexample of this phenomenon Any new programming system attempting to gain ac-ceptance has a considerable advantage if it can plug into some existing ecosystem, andone of the biggest differences between C# and Java is that C# and the NET Frameworkpositively embrace the Windows platform, while Java goes out of its way to insulatedevelopers from the underlying OS
If you’re writing code to run on a specific operating system, it’s not especially helpfulfor a language to cut you off from the tools and components unique to your chosenplatform Rather than requiring developers to break with the past, NET offers con-tinuity by making it possible to work directly with components and services either builtinto or built for Windows Most of the time, you won’t need to use this—the classlibrary provides wrappers for a lot of the underlying platform’s functionality However,
if you need to use a third-party component or a feature of the operating system thatdoesn’t yet have a NET wrapper, the ability to work with such unmanaged featuresdirectly from managed code is invaluable
Trang 31While NET offers features to ease integration with the underlying
plat-form, there is still support for non-Windows systems Microsoft’s
Sil-verlight can run C# and VB.NET code on Mac OS X as well as Windows.
There’s an open source project called Mono which enables NET code
to run on Linux, and the related Moonlight project is an open source
version of Silverlight So the presence of local platform integration
fea-tures doesn’t stop C# from being useful on multiple platforms—if you
want to target multiple operating systems, you would just choose not
to use any platform-specific features.
So the biggest philosophical difference between C# and Java is that C#
provides equal support for direct use of operating-system-specific
features and for platform independence Java makes the former
dispro-portionately harder than the latter.
The latest version of C# contains features that enhance this capability further Several
of the new C# 4.0 features make it easier to interact with Office and other Windowsapplications that use COM automation—this was a weak spot in C# 3.0 The relativeease with which developers can reach outside the boundaries of managed code makesC# an attractive choice—it offers all the benefits of managed execution, but retains theability to work with any code in the Windows environment, managed or not
C# 4.0, NET 4, and Visual Studio 2010
Since C# favors general-purpose language features designed to be composed with oneanother, it often doesn’t make sense to describe individual new features on their own
So rather than devoting sections or whole chapters to new features, we cover them incontext, integrated appropriately with other, older language features The sectionyou’re reading right now is an exception, of course, and the main reason is that weexpect people already familiar with C# 3.0 to browse through this book in bookstoreslooking for our coverage of the new features If that’s you, welcome to the book! If youlook in the Preface you’ll find a guide to what’s where in the book, including a sectionjust for you, describing where to find material about C# 4.0 features
That being said, a theme unites the new language features in version 4: they support dynamic programming, with a particular focus on making certain interoperability sce-narios simpler For example, consider the C# 3.0 code in Example 1-3 that uses part
of the Office object model to read the Author property from a Word document
Example 1-3 The horrors of Office interop before C# 4.0
static void Main(string[] args)
{
var wordApp = new Microsoft.Office.Interop.Word.Application();
object fileName = @"WordFile.docx";
object missing = System.Reflection.Missing.Value;
C# 4.0, NET 4, and Visual Studio 2010 | 7
Trang 32object readOnly = true;
Microsoft.Office.Interop.Word._Document doc =
wordApp.Documents.Open(ref fileName, ref missing, ref readOnly,
ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing);
object docProperties = doc.BuiltInDocumentProperties;
Type docPropType = docProperties.GetType();
object authorProp = docPropType.InvokeMember("Item",
BindingFlags.Default | BindingFlags.GetProperty,
null, docProperties,
new object[] { "Author" });
Type propType = authorProp.GetType();
string authorName = propType.InvokeMember("Value",
BindingFlags.Default |BindingFlags.GetProperty,
null, authorProp,
new object[] { }).ToString();
object saveChanges = false;
doc.Close(ref saveChanges, ref missing, ref missing);
Console.WriteLine(authorName);
}
That’s some pretty horrible code—it’s hard to see what the example does because thegoal is lost in the details The reason it is so unpleasant is that Office’s programmingmodel is designed for dynamic languages that can fill in a lot of the details at runtime.C# 3.0 wasn’t able to do this, so developers were forced to do all the work by hand.Example 1-4 shows how to do exactly the same job in C# 4.0 This is a lot easier tofollow, because the code contains only the relevant details It’s easy to see the sequence
of operations—open the document, get its properties, retrieve the Author property’svalue, and close the document C# 4.0 is now able to fill in all the details for us, thanks
to its new dynamic language features
Example 1-4 Office interop with C# 4.0
static void Main(string[] args)
{
var wordApp = new Microsoft.Office.Interop.Word.Application();
Microsoft.Office.Interop.Word._Document doc =
wordApp.Documents.Open("WordFile.docx", ReadOnly: true);
dynamic docProperties = doc.BuiltInDocumentProperties;
string authorName = docProperties["Author"].Value;
doc.Close(SaveChanges: false);
Console.WriteLine(authorName);
}
Trang 33This example uses a couple of C# 4.0 features: it uses the new dynamic keyword forruntime binding to members It also uses the support for optional arguments TheOpen and Close methods take 16 and 3 arguments, respectively, and as you can see fromExample 1-3, you need to provide all of them in C# 3.0 But Example 1-4 has onlyprovided values for the arguments it wants to set to something other than the default.Besides using these two new features, a project containing this code would usually be
built using a third new interop feature called no-PIA There’s nothing to see in the
preceding example, because when you enable no-PIA in a C# project, you do not need
to modify your code—no-PIA is essentially a deployment feature In C# 3.0, you had
to install special support libraries called primary interop assemblies (PIAs) on the target
machine to be able to use COM APIs such as Office automation, but in C# 4.0 you no
longer have to do this You still need these PIAs on your development machine, but the
C# compiler can extract the information your code requires, and copy it into yourapplication This saves you from deploying PIAs to the target machine, hence the name,
“no-PIA”
While these new language features are particularly well suited to COM automationinterop scenarios, they can be used anywhere (The “no-PIA” feature is narrower, butit’s really part of the NET runtime rather than a C# language feature.)
Summary
In this chapter we provided a quick overview of the nature of the C# language, and weshowed some of its strengths and how the latest version has evolved There’s one lastbenefit you should be aware of before we get into the details in the next chapter, andthat’s the sheer quantity of C# resources available on the Internet When the NETFramework first appeared, C# adoption took off much faster than the other NETlanguages Consequently, if you’re searching for examples of how to get things done,
or solutions to problems, C# is an excellent choice because it’s so well represented inblogs, examples, tools, open source projects, and webcasts—Microsoft’s own docu-mentation is pretty evenhanded between C# and VB.NET, but on the Web as a whole,you’re far better served if you’re a C# developer So with that in mind, we’ll now look
at the fundamental elements of C# programs
Summary | 9
Trang 35CHAPTER 2
Basic Programming Techniques
To use a programming language, you must master the fundamentals You need to derstand the elements required to construct a working program, and learn how to usethe development tools to build and run code You also need to become familiar withthe everyday features for representing information, performing calculations, and mak-ing decisions This chapter will introduce these core features of the C# language
un-Getting Started
We’ll be working in Visual Studio, the Microsoft development environment There areother ways to build C# programs, but Visual Studio is the most widely used and it’sfreely available, so we’ll stick with that
If you don’t have Visual Studio, you can download the free Express
edition from http://www.microsoft.com/express/.
In the first part of this chapter, we’ll create a very simple program so that you can seethe bare minimum of steps required to get up and running We’ll also examine all ofthe pieces Visual Studio creates for you so that you know exactly what the developmentenvironment is doing for you And then we’ll build some slightly more interesting ex-amples to explore the C# language
To create a new C# program, select the File New Project menu option, or just use theCtrl-Shift-N shortcut This will open Visual Studio’s New Project dialog, shown inFigure 2-1, where you can pick the kind of program you want to build In the InstalledTemplates list on the lefthand side, ensure that the Visual C# item is expanded, andinside that, select the Windows item—applications that run locally on Windows arethe easiest to create We’ll get into other kinds of programs such as web applicationslater in the book
11
Trang 36In the dialog’s center, select the Console Application template This creates an fashioned command-line application that runs in a console window It might not bethe most exciting kind of program, but it’s the easiest to create and understand, sothat’s where we’ll start.
old-You need to pick a name for your program—by default, Visual Studio will suggestsomething unimaginative such as ConsoleApplication1 In the Name field near the bot-tom of the dialog, type HelloWorld (OK, so that’s equally unimaginative, but at leastit’s descriptive.) Visual Studio also wants to know where you’d like to put the project
on your hard disk—put it wherever you like It can also create a separate “solution”directory That’s something you’d do in a larger program made up of multiple com-ponents, but for this simple example, you want the “Create directory for solution”checkbox to be unchecked
When you click the OK button, Visual Studio will create a new project, a collection of
files that are used to build a program C# projects always contain source code files, butthey often include other types of files, such as bitmaps This newly created project will
contain a C# source file called Program.cs, which should be visible in Visual Studio’s
text editor In case you’re not following along in Visual Studio as you read this, thecode is reproduced in Example 2-1 By the way, there’s no particular significance to the
filename Program.cs Visual Studio doesn’t care what you call your source files; by convention, they have a cs extension, short for C#, although even that’s optional Figure 2-1 Visual Studio’s New Project dialog
Trang 37Example 2-1 The code in a freshly created console application
Example 2-2 The traditional first example, “Hello, world”
a key to dismiss the window
Don’t use Debug Start Debugging or F5—this will run the application
in Visual Studio’s debugging mode, which doesn’t keep the window
open once the application has finished That’s not helpful for this
ex-ample, which will most likely run to completion and then close the
window before you’ve had a chance to see the output.
Getting Started | 13
Trang 38Now that we have a complete program, let’s look at the code to see what each part isfor—all of the pieces are things you’ll deal with every time you write in C# Starting
from the top, Program.cs has several lines beginning with using:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
These using directives help the C# compiler work out what external code this particular
source file will be using No code is an island—to get any useful work done, yourprograms will rely on other code All C# programs depend on the NET Frameworkclass library, for example: the one line of code we added to our program uses the classlibrary to display a message Using directives can declare an intent to use classes fromany library—yours, Microsoft’s, or anyone’s All the directives in our example startwith System, which indicates that we want to use something from the NET Framework.This text that follows the using keyword denotes a namespace.
Namespaces and Types
The NET Framework class library is big To make it easier to find your way aroundthe many services it offers, the library is split into namespaces For example, the System.IO namespace offers I/O (Input/Output) services such as working with files ondisk, while System.Data.SqlClient is for connecting to a SQL Server database
A namespace contains types A type typically represents either a kind of information or
a kind of object For example, there are types that provide the core forms of informationused in all programs, such as System.String which represents text, or the various nu-meric types such as System.Double or System.Int32 Some types are more complex—for example, the System.Net.HttpWebRequest class represents an HTTP request to besent to a web server A few types do not represent any particular thing, but simply offer
a set of services, such as the System.Math class, which provides mathematical functionssuch as Sin and Log, and constants such as π or the base of natural logarithms, e (We
will explore the nature of types, objects, and values in much more detail in the nextchapter.)
All types in the NET Framework class library belong to a namespace The purpose of
a using directive is to save you from typing the namespace every single time you need
to use a class For example, in a file that has a using System; directive you can just writeMath.PI to get the value of π, instead of using the full name, System.Math.PI You’re notrequired to write using directives, by the way—if you happen to enjoy typing, you’refree to use the fully qualified name But since some namespaces get quite long—forexample, System.Windows.Media.Imaging—you can see how the shorthand enabled by
a using directive can reduce clutter considerably
You might be wondering why namespaces are needed at all if the first thing we usually
do is add a bunch of using directives to avoid having to mention the namespace
Trang 39anywhere else One reason is disambiguation—some type names crop up in multipleplaces For example, the ASP.NET web framework has a type called Control, and so
do both WPF and Windows Forms They represent similar concepts, but they are used
in completely different contexts (web applications versus Windows applications) though all of these types are called Control, they are distinct thanks to being in differentnamespaces
Al-This disambiguation also leaves you free to use whatever names you want in your owncode even if some names happen to be used already in parts of the NET class libraryyou never knew existed Since there are more than 10,000 types in the framework, it’sentirely possible that you might pick a name that’s already being used, but namespacesmake this less of a problem For example, there’s a Bold class in NET, but if you happennot to be using part of the library it belongs to (WPF’s text services) you might wellwant to use the name Bold to mean something else in your own code And since NET’sown Bold type is hidden away in the System.Windows.Documents namespace, as long asyou don’t add a using directive for that namespace you’re free to use the name Boldyourself to mean whatever you like
Even when there’s no ambiguity, namespaces help you find your way around the classlibrary—related types tend to be grouped into one namespace, or a group of relatednamespaces (For example, there are various namespaces starting with System.Web con-taining types used in ASP.NET web applications.) So rather than searching throughthousands of types for what you need, you can browse through the namespaces—thereare only a few hundred of those
You can see a complete list of NET Framework class library
namespa-ces, along with a short description of what each one is for, at http://msdn
.microsoft.com/library/ms229335.
Visual Studio adds four namespace directives to the Program.cs file in a new console
project The System namespace contains general-purpose services, including basic datatypes such as String, and various numeric types It also contains the Console type ourprogram uses to display its greeting and which provides other console-related services,such as reading keyboard input and choosing the color of your output text
The remaining three using directives aren’t used in our example Visual Studio addsthem to newly created projects because they are likely to be useful in many applications.The System.Collections.Generic namespace contains types for working with collec-tions of things, such as a list of numbers The System.Linq namespace contains typesused for LINQ, which provides convenient ways of processing collections of informa-tion in C# And the System.Text namespace contains types useful for working with text.The using directives Visual Studio adds to a new C# file are there just to save you sometyping You are free to remove them if you happen not to be using those namespaces.And you can add more, of course
Namespaces and Types | 15
Trang 40Removing Unwanted Using Directives
There’s a quick way to remove unwanted using directives If you right-click anywhere
on your C# code, the context menu offers an Organize Usings item This opens asubmenu that includes a Remove Unused Usings item—this works out which usingdirectives are surplus to requirements, and removes them The submenu offers anotheroption designed to appeal to those who like to keep their source code tidy—its Removeand Sort entry can remove unused using statements and then sort the rest into alpha-betical order This menu is shown in Figure 2-2
Figure 2-2 Tidying up using directives
The using directives are not the end of our simple program’s encounter with spaces In fact, the very next line of code after these directives is also concerned withnamespaces:
* Strictly speaking, you can leave out the namespace, in which case your types will end up in the so-called
global namespace But this is considered a poor practice—you’ll normally want your own code to reap the
same benefits that class libraries get from namespaces.