Programming Microsoft Visual C# 2005: The LanguagebyDonis Marshall Microsoft Press 2006 704 pagesISBN:0735621810 Offering expert guidance, hands-on programminginstruction, and practical
Trang 1Programming Microsoft Visual C# 2005: The Language
byDonis Marshall Microsoft Press 2006 (704 pages)ISBN:0735621810
Offering expert guidance, hands-on programminginstruction, and practical examples, this
straightforward book will help both new andexperienced developers advance their proficiency indeveloping applications for Microsoft Windows and theWeb
Trang 3developing applications for Microsoft Windows and the Web.
Discover how to:
Refine class usage with inheritance,
polymorphism, and other strategies
Implement generics to define a type-safe data structure
Work with stacks, queues, arrays, dictionaries, and other collections
Use iterators to implement and standardize
enumerator patterns
Know when to catch exceptions—and handle them locally or propagate them
Interrogate metadata and facilitate late binding
by using reflection
Synchronize threads with locks, events, mutexes, and other tools
Trang 4explore advanced debugging techniques and tools
About the Author
Donis Marshall is a trainer, a consultant and an author with 20 years of development experience and an in- depth background on Microsoft NET technologies He
Trang 5Language
Donis Marshall
PUBLISHED BY Microsoft Press A Division of Microsoft Corporation One Microsoft Way Redmond, Washington 98052-6399
International directly at fax (425) 936-7329 Visit our Web site at
www.microsoft.com/mspress Send comments to
mspinput@microsoft.com
Microsoft, IntelliSense, Microsoft Press, MSDN, Visual Basic, Visual C#,Visual Studio, the Visual Studio logo, Win32, Windows, Windows CE, theWindows logo, Windows NT, and WinFX are either registered trademarks
or trademarks of Microsoft Corporation in the United States and/or othercountries Other product and company names mentioned herein may be
Trang 6The example companies, organizations, products, domain names, e-mailaddresses, logos, people, places, and events depicted herein are
fictitious No association with any real company, organization, product,domain name, e-mail address, logo, person, place, or event is intended
or should be inferred
This book expresses the author's views and opinions The informationcontained in this book is provided without any express, statutory, or
implied warranties Neither the authors, Microsoft Corporation, nor itsresellers, or distributors will be held liable for any damages caused oralleged to be caused either directly or indirectly by this book
of all a compassionate person He was a giant amongst men and
touched innumerable lives His three sons, including myself, miss him every day.
Acknowledgments
Programming Microsoft Visual C# 2005: The Language was completed
with the collaboration of several people I am credited on the cover, butthe contribution of others is no less important I want to especially
acknowledge the contributions of Valerie Woolley, Ben Ryan, and JimRogers If possible, they would also receive cover credit Valerie was theproject manager and provided support, encouragement, patience, and
Trang 7appreciated Jim Rogers was the technical editor and diligently reviewedhundreds of pages of manuscript and code He helped assure the superbquality of the book
I also want to thank John Bruno, who is an exceptional engineer, for
reviewing and commenting on each chapter, which was very helpful
Writing a book is an all-consuming project Unfortunately, much of thisburden is carried by friends and loved ones I appreciate the patienceand support of my mother, Lynn, and of my friends Herb, Jr., Chuck, andPatty, along with a long list of other friends who were treated shabbilyduring this project Thanks for your understanding
Finally, I want to acknowledge my children: Jason, Kristen, and Adam.They make every day special They are my motivation A special
acknowledgment is reserved for Jason During most of this project, Jasonwas stationed in Iraq as a Marine He recently returned home safely Weare proud of you
Donis Marshall
Donis Marshall is currently one of the few trainers endorsed by MicrosoftGlobal Learning Services to conduct Microsoft technology classes forMicrosoft employees In this capacity, Mr Marshall travels internationally,delivering dozens of classes to Microsoft developers and engineers in theUnited States, Europe, and Asia His repertoire includes classes on
Advanced NET UMD Debugging, Advanced NET Debugging
workshops, NET Design and Architecture, Visual Basic NET
Programming, NET Interoperability and Security, NET Web Services,and ASP.NET He also teaches NET classes at Autodesk, NCCI, andNASA
Trang 9Studio IDE has also been enhanced in Visual Studio 2005 Microsoftcontinues to expand upon the impressive assortment of rapid applicationdevelopment (RAD) tools that are available The Exception Assistant,code snippets, and visualizers are some of the more notable
advancements, where the emphasis is on providing helpful informationthat markedly increases developer productivity This book details theseand other improvements to previous versions of Visual Studio
A larger portion of the lifetime of an application is spent in maintenanceand debugging Efficient and effective debugging tools and techniquescan facilitate a more robust application, which reduces the need to
debug You can also resolve problems more quickly when they inevitablyoccur A managed application has a managed veneer and an unmanagedunderpinning Debugging requires an understanding of both realms
where a managed application exists: managed and unmanaged From adebugging context, Chapter 12 examines both realms of a managed
application and helps developers understand how to effectively debug amanaged application
Trang 10Programming Microsoft Visual C# 2005: The Language is for developers
who want a comprehensive explanation of Visual C# 2005 or want toexplore a specific aspect of the language It is a composite of chapterssequenced to provide a rational and complete review of the language.Each chapter is also reviewable as an independent unit that
encapsulates a specific topic
depth explanations are offered for even the most ardent developers.Sample code is provided as a complement to the content For casualdevelopers, code is often the clearest explanation of in-depth concepts.Actually, even for professional developers, sample code is often
This book targets both professional and casual developers Practical, in-invaluable For this reason, this book contains reams of code examples
Trang 11Programming Microsoft Visual C# 2005: The Language is organized into
five parts
The first part, "Core Language," introduces the basic concepts of thelanguage Chapter 1 contains a general overview of the language
Chapter 2 introduces types, which include classes and value types
Chapter 3 explains inheritance in C# and the related keywords, such as
virtual, override, sealed, and abstract.
The second part, "Core Skills," covers the core skills required to create aC# application Chapter 4 reviews Visual Studio 2005, which is the
central tool in developing a managed application Chapter 5 explainsarrays and collections It is hard to imagine a competent C# applicationthat does not employ arrays or collections Chapter 6 introduces
generics, which is a new feature of NET Framework 2.0 Chapter 7
pertains to iterators and the capability to enumerate collection-relatedclasses
The third part, "More C# Language," focuses on additional languagefeatures Chapter 8 details managed function pointers, which are
represented by delegates and events in managed code Chapter 9
explains structured exception handling in the run time and within the C#language
The fourth part, "Debugging," is an all-inclusive explanation of debuggingmanaged code The first two chapters in this section provide an internalview of an assembly, which is critical for anyone debugging a managedapplication: Chapter 10 introduces metadata and reflection; Chapter 11 is
an overview of Microsoft intermediate language (MSIL) programming.Chapter 12 discusses debugging with Visual Studio, which is the
preferred debugging environment for most developers Finally, Chapter
13 discusses advanced debugging using the MDbg, Windbg, and SOSdebugger extensions
The final part is "Advanced Concepts." Chapter 14 covers managed
memory and garbage collection in the managed environment Chapter 15
Trang 12explains unsafe code and direct pointer manipulation This chapter alsodiscusses calling functions that are in unmanaged (native) libraries.
Trang 13You'll need the following hardware and software to build and run the codesamples for this book:
Microsoft Windows XP with Service Pack 2, Microsoft WindowsServer 2003 with Service Pack 1, or Microsoft Windows 2000with Service Pack 4
Microsoft Visual Studio 2005 Standard Edition or Microsoft VisualStudio 2005 Professional Edition
600 MHz Pentium or compatible processor (1 GHz Pentium
recommended)
192 MB RAM (256 MB or more recommended)
Video (800 × 600 or higher resolution) monitor with at least 256colors (1024 × 768 High Color 16-bit recommended)
Trang 14As technologies related to this book are updated, links to additionalinformation will be added to the Microsoft Press Technology UpdatesWeb page Visit this page periodically for updates on Visual Studio 2005and other technologies:
http://www.microsoft.com/mspress/updates/
Trang 15All the code samples discussed in this book can be downloaded from thebook's companion content Web page at the following address:
http://www.microsoft.com/mspress/companion/0-7356-2181-0/
Trang 16Every effort has been made to ensure the accuracy of this book and thecompanion content As corrections or changes are collected, they will beadded to a Microsoft Knowledge Base article To view the list of knowncorrections for this book, visit the following article:
http://support.microsoft.com/kb/905044
Microsoft Press provides support for books and companion content at thefollowing Web site:
http://www.microsoft.com/learning/support/books/
Questions and Comments
If you have comments, questions, or ideas regarding the book or thecompanion content, or questions that are not answered by visiting theprevious sites, please send them to Microsoft Press via e-mail to
Trang 17Part I: Core Language
Trang 18Chapter 1: Introduction to Visual C# Programming
Chapter 2: Types
Chapter 3: Inheritance
Trang 19Chapter 1: Introduction to Visual C# Programming
Trang 20Microsoft Visual C# 2005 is an object-oriented programming languageused to develop applications targeting the NET environment
Programming languages are not unlike natural languages such as
Spanish, Latin, French, Chinese, or English—human languages that arewritten or spoken Each natural language includes rules that describeproper syntax and structure; we use these rules to convey cohesive
of competency in FORTRAN, Turkish, English, COBOL, Spanish,
German, C, and other languages (not necessarily in that order), I speakfrom experience Languages are languages When you're learning a
human language, your goals are literacy and being able to have a
conversation If, as a student of French, you can sit in a Parisian café andread the menu while discussing current events with the locals, your
language skills are a fait accompli The goal of this chapter is the same:
for you to become conversational in C#
Learning a language typically begins with core elements of language InEnglish, these elements include consonants, vowels, nouns, verbs,
adjectives, phrases, and sentences They represent the building blocks ofthe language; you cannot read, write, or speak English without a
fundamental understanding of these language components The key
elements of C# are symbols and tokens, keywords, expressions,
statements, functions, and classes Effective C# programming requires,
of course, a fundamental understanding of these elements, which thischapter will provide
As you know, a sentence in English is more than random words
terminated with a period Likewise, in C#, a programming statement is
Trang 21syntax orders the clauses of a for statement According to C# syntax, the previous for statement should be structured like this: for(int i=0;i<5;++i).
Understanding the underlying language syntax is equally important fornatural and programming languages This chapter will also provide thebasic syntax of the C# language
Mandarin Chinese is a tonal language, whereas English is a stress
language Learning Chinese is more than simply assimilating new wordsand sentence structures You must also learn tones because the
meaning of a Chinese word can change based on tone Speaking
Chinese with English enunciation would be confusing and amusing atbest Similarly, C# is an object-oriented language, not a procedural
language (more on this difference later) C#, C++, Java, SmallTalk, Eiffel,and other object-oriented languages are only as effective as your
appreciation of object-oriented concepts and programming techniques Irecommend a basic knowledge of object-oriented analysis and designconcepts as a complement to the newly acquired C# skills this book willgive you
Finally, languages do not emerge spontaneously Natural languages havebeen evolving for nearly 150,000 years, and knowing the heritage of andthe influences on a language can be informative and helpful For
example, English, French, German, Yiddish, and related languages areheavily influenced by their Latin language heritage As such, they havecommon words, syntax, and structures that are characteristic of the Latinmetalanguage The origin of C# does not date back centuries, but an
Trang 22understanding of its evolution is invaluable.
Trang 23From the time when the first natural language appeared, hundreds ofthousands of languages have emerged Many of these languages arenow extinct, leaving about six thousand languages that are currently
spoken Some of these languages are similar and grouped by
classification Other languages are quite distinct, such as Kora, whichincorporates a series of click sounds and is spoken by bushmen in Africa
A list of programming languages is modest when compared with the
catalogue of natural languages Beginning in the 1940s with Plankalkül,more than 1,000 programming languages have been documented Likenatural languages, the variety and diversity of these languages is
impressive: the succinctness of assembler, the verbosity of COBOL, andthe efficiency of C For a comprehensive list of programming languages,visit this link: http://oop.rosweb.ru/Other/
The motivations that inspire the creation of languages are diverse:
FORTRAN was created for scientific analysis, COBOL for building
business applications, RPG for report generation, and so on Some
languages serve as refinements of earlier languages CPL combined thebest ingredients of several languages, including ALGOL, FORTRAN, andCOBOL C# is an independently developed, object-oriented languageand a member of the C family of languages It shares similar syntax andsome concepts with other C-family languages; more important, however,C# has few if any vestiges of procedural programming, in which the basicprogramming element is the procedure (that is, a named sequence ofstatements, such as a routine, subroutine, or function) Unfortunately,C++ inherited many of the artifacts of procedural programming from C.C#, however, was designed to be a purely object-oriented language
ALGOL is arguably the most influential programming language in history.The language was introduced in 1958 but became popular when ALGOL-
60 was released in 1960 ALGOL quickly became the dominant language
in Europe during the 1960s Its impact on future languages such as
Pascal, C, and Java is undeniable—these languages' grammatical syntaxborrows heavily from ALGOL I've programmed professionally in ALGOL,assembler, COBOL, FORTRAN, C, C++, C#, Basic (in various
Trang 2468 extended the language, but the additions increased complexity andfurthered abstraction from hardware This abstraction prevented
developers from easily accessing devices and the lower tiers of the
operating environment Soon, languages were introduced that were lesscomplex and not as abstracted from the architecture One of these newlanguages was C
The journey from ALGOL to C began with CPL CPL, a derivative of
ALGOL-60, was developed at the Computer Lab of Cambridge
University CPL was created in 1963 by David Barron, Christopher
Strachey, and Martin Richards Although CPL is not as abstracted asALGOL, it did maintain one characteristic of ALGOL: complexity MartinRichards introduced Basic CPL (BCPL) in 1967 as a lean version of CPL.Ken Thompson of Bell Labs drafted B in 1970 as the successor to BCPL
B was lighter, faster, and more appropriate for systems programming Cwas developed by Dennis Ritchie, also of Bell Labs, in 1972 C returnedsome of the abstraction removed from B while keeping that languagesimple and quick Although initially consigned to the UNIX operation
system and systems programming, C is a general-purpose language andhas been used for a diverse assortment of applications across a variety
of platforms and operating systems
FORTAN, ALGOL, and COBOL dominated the procedural programminglandscape in the 1960s On a separate track, Simula was created
between 1962 and 1965 by Ole-Johan Dahl and Kristen Nygaard at theNorwegian Computing Center Simula is notable for being the first object-oriented programming (OOP) language It was designed for simulation,but evolved into a general-purpose language Simula introduced theimportant OOP concepts of classes, inheritance, and dynamic binding
Combining aspects of C and Simula, Bjarne Stroustrup introduced C withClasses in 1979 as an enhancement of the C programming language.Later, under Stroustrup's stewardship, C++ was created as a direct
descendant of C with Classes and was publicly recognized in 1983 C++rapidly became the premier object-oriented programming language and
Trang 25C# premiered at the Professional Developers Conference (PDC) held inOrlando, Florida, in 2000 The primary architects of C# were Anders
Hejlsberg, Scott Wiltamuth, Peter Sollichy, Eric Gunnerson, and PeterGolde C# was designed to be a fully object-oriented language focusing
on developing components in a distributed environment and was
launched as part of a larger initiative by Microsoft called Microsoft NET.Underscoring the importance of NET to Microsoft, Bill Gates was thekeynote speaker at the PDC that year I attended the PDC in 2000 andwas both intrigued and motivated by the introduction of NET and C# NET is emblematic of a philosophical change at Microsoft and an
embracing of the standards community
Both NET, as defined by the Common Language Infrastructure (CLI),and C# were submitted to two international standards organizations:
ECMA and ISO/IEC Also, NET and NET languages, described in theCommon Language Specification (CLS), continue the trend toward trulyportable code You can write an application in one environment and run itanywhere else Simultaneously, a new version of Microsoft Visual Studiowas announced: Visual Studio NET Visual Studio NET provides rapidapplication development tools for developing a wide variety of NET
applications
More
Info
For information on the various standards for C# and NET, followthese links The current ECMA standards for the C# LanguageSpecification:http://www.ecma-
international.org/publications/standards/Ecma-334.htm Thecurrent ECMA standards for the Common Language
Infrastructure: http://www.ecma-international.org/publications/standards/Ecma-335.htm Thecurrent ISO/IEC standards for the C# Language Specification:http://www.iso.org/iso/en/CatalogueDetailPage.CatalogueDetail?CSNUMBER=36768&ICS1=35&ICS2=60&ICS3= The currentISO/IEC standards for the CLI:
http://www.iso.org/iso/en/CatalogueDetailPage.CatalogueDetail?CSNUMBER=36769&scopelist=
Trang 26Figure 1-1: Evolution of programming languages from inception to
C#
Trang 27Natural and programming languages consist of both simple and complexstructures The complex structures can be decomposed into simple
elements When learning a new natural language, you probably wouldn'tstart with a review of sentence structure Instead, you probably wouldbegin with an exploration of nouns, verbs, and the simpler components ofthe language For C#, the simpler components are symbols, tokens,
Trang 28Tabs
Tabs—horizontal and vertical—are white space characters Refer to thepreceding explanation of white space
Punctuators
Punctuators separate and delimit elements of the C# language
Punctuators include the semicolon (;), dot (.), colon (:), and comma (,),which are discussed in this section
Semicolon punctuator In a natural language, sentences consist of
phrases and clauses and are units of cohesive expression Sentencesare terminated with a period (.) Statements consist of one or more
expressions and are the commands of the C# programming language.Statements are terminated by a semicolon (;) C# is a free-form language
in which a statement can span multiple lines of source code and start inany position Conversely, multiple statements can be combined on asingle source code line, assuming that each statement is delimited by asemicolon This statement is not particularly good style, but it is
syntactically correct:
int variablea=
variableb +
variablec;
Trang 29also sometimes delimited by commas A statement clause is a
Trang 33<param name="args" />
Trang 34preprocessor statements Preprocessor statements are processed by thenormal C# compiler The term "preproccesor" is used for historical
Trang 35#else #elif #endif
#line #error #warning
#region #endregion #pragma
The preprocessor symbol and subsequent command are optionally
separated with a space, but must be on the same line For this reason,preprocessor commands can be followed only with a single line
comment
Declarative preprocessor directives The declarative preprocessor
directives are #define and #undef, which define and undefine a
preprocessor symbol, respectively Defined symbols are implicitly true,whereas undefined symbols are false Declarative symbols must be
Trang 37Diagnostic directives Diagnostic directives include the #error, #warning,
and #pragma directives The #error and #warning directives display error
and warning messages, correspondingly The diagnostic messages aredisplayed in the Error List window of the Visual Studio IDE Similar to
standard compilation errors, an #error directive prevents the program from compiling; a #warning directive does not prevent the program from
successfully compiling Use conditional directives to conditionally applydiagnostic directives
Trang 38#region directive starts a region, whereas the #endregion directive ends
the region Region directives can be nested The Visual Studio IDE
outlines the source code using region tags In Visual Studio, you cancollapse or expand regions of source code
Trang 39Blocks define the scope of a type, where type is a class, struct, or enum.Additionally, members of the type are listed inside the block
semicolon In most circumstances in which a single statement is allowed,
a statement block can be substituted Statement blocks are prevalent asmethod bodies but are used with conditional and iterative statements
The if statement in the following code, which is a conditional statement, controls a single statement The Console.WriteLine is controlled by the if
Trang 40within a linked list of integers:
class NodeInt {
public NodeInt(int f_Value, NodeInt f_Previous) { m_Value=f_Value;