Thư viện tri thức trực tuyến
Kho tài liệu với 50,000+ tài liệu học thuật
© 2023 Siêu thị PDF - Kho tài liệu học thuật hàng đầu Việt Nam

Computing with C Sharp anh the .NET framework
Nội dung xem thử
Mô tả chi tiết
Computing with C# and the .NET Framework
by Art Gittleman ISBN:0763723398
Jones and Bartlett Publishers © 2003 (753 pages)
Both novice and experienced programmers will find that this
text serves as an accessible and thorough guide to objectoriented and event-driven programming concepts through the
author's spiral teaching approach.
CD Content
Table of Contents
Computing with C# and the .NET Framework
Preface
Chapter 1 - An Introduction to Computing with C#
Chapter 2 - C# Programming Basics
Chapter 3 - Software Engineering with Control Structures
Chapter 4 - More Control Structures and Types
Chapter 5 - Getting Started with Object-Oriented Programming
Chapter 6 - Working with Objects
Chapter 7 - Arrays
Chapter 8 - Event-Driven Programming
Chapter 9 - User Interfaces
Chapter 10 - Inheritance
Chapter 11 - Exception Handling and Input/Output
Chapter 12 - Data Structures
Chapter 13 - Threads and Animation
Chapter 14 - Networking
Chapter 15 - Using a Database
Chapter 16 - ASP.NET
Chapter 17 - XML and Web Services
Appendix A - Binary and Hexadecimal Numbers
Appendix B - Bitwise and Shift Operators
Appendix C - Operator Precedence Table
Appendix D - The ASCII Character Set
Appendix E - Simple Types
Answers to Selected Exercises
Index
List of Figures
List of Code Examples
CD Content
Computing with C# and the .NET Framework
by Art Gittleman ISBN:0763723398
Jones and Bartlett Publishers © 2003 (753 pages)
Both novice and experienced programmers will find that this
text serves as an accessible and thorough guide to objectoriented and event-driven programming concepts through the
author's spiral teaching approach.
CD Content
Table of Contents
Computing with C# and the .NET Framework
Preface
Chapter 1 - An Introduction to Computing with C#
Chapter 2 - C# Programming Basics
Chapter 3 - Software Engineering with Control Structures
Chapter 4 - More Control Structures and Types
Chapter 5 - Getting Started with Object-Oriented Programming
Chapter 6 - Working with Objects
Chapter 7 - Arrays
Chapter 8 - Event-Driven Programming
Chapter 9 - User Interfaces
Chapter 10 - Inheritance
Chapter 11 - Exception Handling and Input/Output
Chapter 12 - Data Structures
Chapter 13 - Threads and Animation
Chapter 14 - Networking
Chapter 15 - Using a Database
Chapter 16 - ASP.NET
Chapter 17 - XML and Web Services
Appendix A - Binary and Hexadecimal Numbers
Appendix B - Bitwise and Shift Operators
Appendix C - Operator Precedence Table
Appendix D - The ASCII Character Set
Appendix E - Simple Types
Answers to Selected Exercises
Index
List of Figures
List of Code Examples
CD Content
Back Cover
Computing with C# demystifies the art of programming with C# through clear explanations and intuitive examples.
Both novice and experienced programmers will find that this text serves as an accessible and thorough guide to objectoriented and event-driven programming concepts. Readers develop a mastery of objects through the author’s spiral
teaching approach: first straightforward examples are presented, then simple class design, and finally the more difficult
aspects of inheritance and polymorphism. The author applies his spiral teaching approach throughout the text, and
readers acquire a meaningful understanding of programming concepts and techniques. This text sets the standard for
today’s C# programming books; readers of all levels will benefit from the rich learning experience that this text
provides.
Distinctive Features:
200 complete, fully annotated programs are included to provide concepts with a concrete embodiment that
facilitates learning.
In addition to basic programming concepts, this text introduces data structures, threads, networking, database
access, XML, Web programming, and Web services.
Readers can practice their skills through the following exercises: Test Your Understanding, Skill Builder, Critical
Thinking, Debugging, Program Modification, Program Design, and more!
Computing with C# and the .NET Framework
Art Gittleman
World Headquarters
Jones and Bartlett Publishers
40 Tall Pine Drive
Sudbury, MA 01776
978-443-5000
www.jbpub.com
Jones and Bartlett Publishers
Canada
2406 Nikanna Road
Mississauga,
ON L5C 2W6
Jones and Bartlett Publishers
International
Barb House, Barb Mews
London W6 7PA
UK
Copyright © 2003 by Art Gittleman
Cover image © Ryan McVay / Getty Images
All rights reserved. No part of the material protected by this copyright may be reproduced or utilized in any
form, electronic or mechanical, including photocopying, recording, or by any information storage and retrieval
system, without written permission from the copyright owner.
Library of Congress Cataloging-in-Publication Data
Gittleman, Art.
Computing with C# and the .NET framework / Arthur Gittleman.
p. cm.
ISBN 0-7637-2339-8
1. C# (Computer program language) 2. Microsoft .NET Framework. I. Title.
QA76.73.C154 G58 2003
005.13'3--dc21 2002040703
Editor-in-Chief, College: J. Michael Stranz
Production Manager: Amy Rose
Associate Editor: Theresa DiDonato
Associate Production Editor: Karen C. Ferreira
Senior Marketing Manager: Nathan J. Schultz
Production Assistant: Jenny L. McIsaac
Cover Design: Kristin E. Ohlin
Composition: Northeast Compositors
Design: Anne's Books
Printing and Binding: Courier Westford
Cover Printing: Jaguar Advanced Graphics
This book was typeset in QuarkXpress 4.1 on a Macintosh G4. The font families used were Times, Frutiger,
and Impress. The first printing was printed on 45# Highland Plus.
07 06 05 04 03 10 9 8 7 6 5 4 3 2 1
To Charlotte with love
Preface
C# and the .NET Framework support a new, integrated, powerful Internet programming model. We no longer
need to use Visual Basic for rapid application development and forms, C++ for object-oriented applications,
and ASP for the Web. We can use C# for all, and with the .NET Framework we have a platform with a huge
library that can integrate applications across the Internet.
This text teaches C# from the beginning, but includes enough material for a two-term course covering more
advanced topics. It teaches the concepts of computing necessary for a CS-1 course, but allows those with
prior experience programming in another language to proceed quickly over the earlier chapters to learn the
exciting C# language and .NET Framework in depth.
Core topics include C# basics, control structures, types, object-oriented programming, and arrays. Next come
event-driven programming, user interfaces, and inheritance. Additional topics include exception handling,
files, data structures, threads, animation, networking, databases, web programming with ASP.NET, and XML
and web services. The later chapters can, for the most part, be studied independently, so an instructor has
flexibility in the choice of topics for a more advanced course.
I believe one learns best from example, and, therefore, each chapter has many complete programs. As
programmers we learn to add comments to our code, but for pedagogical purposes where comments would
be so detailed as to clutter the code, I prefer to use notes. Each note contains a longer explanation of a key
line of code, and appears just after the code, allowing easier reading of the code itself. By using notes in this
way, I also avoid cluttering the text with detailed code explanations and can focus on explaining concepts.
One also learns by doing. To facilitate learning I include many varied exercises. Test Your Understanding
Exercises at the end of each section give readers a chance to assimilate the material immediately. Answers
to the odd-numbered exercises appear at the end of the text, and answers to the even-numbered exercises
are available with code for all program examples on a Student Resource CD included with the text. This CD
also includes the .NET framework SDK.
I include Skill Builder and Critical Thinking exercises at the end of most chapters to allow readers to master
new concepts. Answers to these appear at the end of the book. A debugging exercise at the end of most
chapters helps develop this necessary skill.
Program Modification exercises allow readers to tackle this common task. Program Design exercises provide
practice including the entire development process.
One can debate endlessly the best way to introduce objects. I like to present objects early, but using a spiral
approach so students build a sound foundation before delving into the details. Thus I start with an intuitive
example in Chapter 5 and continue to show, using UML, how to design a class and code it in C#. I defer some
concepts to Chapter 6, and the more difficult inheritance concepts to Chapter 9.
I thank reviewers
Gerald Baumgartner, The Ohio State University
David Binkley, Loyola College
Corinne Hoisington, Central Virginia Community College
Kenrick Mock, University of Alaska Anchorage
for their many perceptive comments and suggestions that did much to improve the manuscript. It has bee a
great pleasure working with the very helpful and amiable CS team at Jones and Bartlett, including Michael
Stranz, Theresa DiDonato, Amy Rose, Jenny McIsaac, and Karen Ferreira.
The web site for this book is
http://computerscience.jbpub.com/csharp
I will post errata as soon as I become aware of them. Please email any corrections to me at
Chapter 1: An Introduction to Computing with C#
Download CD Content
Overview
Once upon a time, giant digital computers filled large rooms with their thousands of vacuum tubes. They were
slow beasts, but looked awesome. In the years since electronic digital computers were first developed in the
1940s, computers have dramatically decreased in size and increased in computing power. Starting as a tool
for science and engineering, computers have become an essential part of our society.
Studying computing challenges us to keep up with rapid technological change. With C# (pronounced C
sharp) we can learn the basic techniques of programming that have brought us to this point, and go forward
with object-oriented, interactive, graphical, event-driven programming, networking, and web services that take
us to the future.
Objectives
Introduce basic computing concepts
Survey C# history, its features, and how it works
Introduce the elements of a C# program
Introduce the program development process
1.1 Introduction to Computing
Hardware
A computer has several basic components (see Figure 1.1). The processor executes programs stored in
memory, using the memory to store data needed in computations. External storage, including disk drives,
holds programs and data. Input devices such as a keyboard and a mouse allow user interaction. Output
devices display results. Changing technology improves the performance of these components and provides
new types, but current commercial computers have this organization.
Figure 1.1: A computer system
Software
Software consists of the programs the computer executes. The operating system software makes it much
easier for us to use the computer. It provides an interface to the hardware for us, so that each of us does not
have to write programs to read input from the keyboard, write output to the screen, or create files on the hard
disk. An operating system can be relatively simple, providing few services, or it can be a huge program with
many bells and whistles for us to use.
Programmers appreciate utility programs such as editors that allow us to create or modify programs and
compilers that translate programs from one language to another to facilitate their execution. End users run
word processors, spreadsheets, games, browsers, and many other applications. Businesses rely on
computer software to serve customers and for the businesses' accounting, payroll, and other management
needs.
The processor executes software using its specially designed instruction set. Each instruction is simple so that
it may take hundreds, thousands, or millions of instructions to implement the tasks we want our software to
perform. Each instruction has several parts. These parts specify the operation (addition, for example) that
the instruction performs, and any operands that it uses, such as the numbers to add. Each memory location
has a numerical address. High-level languages such as C# provide instructions to perform the equivalent of
many low-level machine instructions.
High-Level Languages
Each processor has its own instruction set that uses numerical codes for the operators and numerical
addresses for the operations. Each instruction performs one basic step such as an addition, a load, or a store.
Programming using a processor's instruction set would make it difficult to accomplish any but the simplest
tasks. Moreover, we would have to write such a program all over again for the instruction set of a different
processor. A program using processor ABC's instruction set will not run on processor XYZ, and vice versa.
A high-level language allows us to express the computation in a more understandable form, combining
several steps into one expression, and to write a program that we can implement on many types of
processors. For example, we can express an addition as
totalSalary = baseSalary + bonus;
Figure 1.2: Translating a high-level program
and write more complicated statements such as
totalScore =
(judge1Score + judge2Score + judge3Score) * difficulty;
which represents the total score obtained by first adding the scores of three judges, and then multiplying that
sum by a difficulty factor. We use the asterisk, *, to denote multiplication.
Compilers
A compiler translates a program from one language to another. If we want to write a program in a high-level
language and run it on processor ABC, we can use a compiler to translate our high-level program to an
equivalent program using the instruction set of processor ABC. Each high-level statement will usually
translate to several processor ABC instructions. Figure 1.2 shows this process.
To run the same program on processor XYZ we would need another compiler that translates from the highlevel language to the instruction set of processor XYZ. The high-level program is called the source code, and
the translated program is called the executable code or the binary code (reflecting its use of the binary
number system to represent operators and operands.) Implementations of the C and C++ languages usually
use compilers to produce executable code for specific processors.
Compilers are indispensable tools for program developers, but end users have no desire to use them. A
player of a game wants a program that will run—an executable program. The vendor of that game must
provide executable versions of the game for each processor.
Interpreters
An interpreter is a program that executes the code rather than translating it to another language. For
example, an interpreter would execute the statement
totalSalary = baseSalary + bonus;
by finding the values of baseSalary and bonus, adding them, and storing the result in totalSalary. In
this example, the interpreter executes a high-level language statement. The BASIC language, used on early
personal computers that had insufficient memory to support the compilation process, was typically
implemented by an interpreter.
We could also use an interpreter to allow one machine to simulate the instructions of another, as shown in
Figure 1.3. For example, we could write a program that executes, on processor XYZ, programs written using
processor ABC's instruction set. Many Java implementations use a combination of compilation and
interpretation, as did the first implementations of the Pascal language.
Figure 1.3: An interpreter executing each high-level statement
Networks
Thus far we have focused on the software and hardware for a single computer. With the advent of the
Internet, computers easily communicate with other computers in the same office, the same company, or at
remote sites all over the world. Many of us use email more than we use regular mail or the telephone. A
computer may be connected by cable to other computers in a network, or use a modem to connect over
telephone lines.
The Internet is a vast network of networks over which we use familiar services such as email and file transfer.
The World Wide Web, a rapidly growing part of the Internet, uses hypertext to create a web of links from one
computer to another. Hypertext, which we discuss later in the text, allows us to include images, sounds,
formatted text, and links to other computers in web pages which we display using a browser. Many use
browser software as their primary access to computers. Web services allow computers to communicate with
one another.
The BIG Picture
Operating system software handles the details of input, output, and files. Each hardware processor uses its
own low-level instruction set. Higher-level languages allow programmers to write statements that are more
meaningful. A compiler translates a program in a high-level language to the instruction set for a specific
processor. An interpreter executes the high-level code directly.
Test Your Understanding
1. Describe each component of the computer that you will be using to program in C#. What is the
function of each?
2. List several software applications you have used or would like to use. Identify each as an
operating system, word processor, game, etc.
3. What do we call the type of program that translates a program in a high-level language to an
equivalent program in another language?
4. What do we call the type of program that executes another program?
Answers
3. A compiler.
1.2 The .NET Framework
Microsoft developed the C# language along with the .NET Framework, a new computing platform that
simplifies application development in the distribution environment of the Internet. They designed the .NET
Framework to fulfill the following objectives[1]
:
To provide a consistent object-oriented programming environment whether object code is stored and
executed locally, executed locally but Internet-distributed, or executed remotely.
To provide a code-execution environment that minimizes software deployment and versioning conflicts
To provide a code-execution environment that guarantees safe execution of code, including code created
by an unknown or semitrusted third party
To provide a code-execution environment that eliminates the performance problems of scripted or
interpreted environments
To make the developer experience consistent across widely varying types of applications, such as
Windows-based applications and Web-based applications
To build all communication on industry standards to ensure that code based on the .NET Framework can
integrate with any other code
The .NET Framework objective meets the needs of professional developers. This text presents only a small
part of the .NET Framework, but we cannot climb the mountain until we take the first steps.
The two main parts of the .NET Framework are the Common Language Runtime and the .NET Framework
class library.
The Common Language Runtime
The Common Language Runtime (CLR) manages the execution of code and provides services that make the
execution of code easier. "Runtime" means that code is running, which is another way of saying it is being
executed. "Common Language" means that this runtime manages the execution of code written in several
languages that share the services provided.
Microsoft developed C# to take advantage of the CLR. Its features work especially well with the CLR. The
popular Visual Basic language evolved to Visual Basic .NET, which is an object-oriented language that takes
advantage of the CLR. Visual Basic programmers have to learn many new features to take advantage of the
CLR using Visual Basic .Net. C++, like its C predecessor, has many capabilities that do not fit into the new
approach. A version of C++, called managed C++, adapts C++ to work with the CLR, so C++ programmers
can integrate code with other CLR users.
We call code that uses the CLR managed code. The Common Type System defines the types of data that
managed code can use. A Common Language Specification (CLS) defines features that every language for
developing managed code must provide. Programmers who use only features in the Common Language
Specification can build an application combining programs in different languages. They will know that if they
use a feature in one language, a program in another language will also be able to use that same construct.
To give a simplified example, consider numbers. Suppose we have space for only 10 numbers. If we use only
nonnegative numbers, we can use 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9. If we need to include both positive and
negative values, we would choose –5, –4, –3, –2, –1, 0, 1, 2, 3, and 4. The unsigned type allows us to use
larger values, but the signed type allows us to use negative values. In an analogous situation, the Common
Type System provides both unsigned and signed types, but only requires that languages provide signed types
to satisfy the Common Language Specification.
A developer who uses only signed types can expect every language that follows the CLS to interoperate with
the code produced. A developer who uses unsigned types may produce code that another language that
follows the CLS is not required to support.
A big problem facing developers is the many different types of processors that run code. Windows,
Macintosh, and Unix machines use a wide variety of hardware, as do personal digital assistants, cell phones,
large computers, and other platforms. One way to make a program work on each of these devices is to
translate the program to the native instruction set for that device. Say we have 10 programming languages
and 10 devices. Using this approach, in the worst case[2]
we would need 100 compilers to translate programs
in each of the 10 languages to native code for each of the 10 devices. Figure 1.4 diagrams this jumble of
compilers.
Figure 1.4: Compiling three languages to native code for three machines
Another approach, used by the CLR, is to provide an intermediate language that is much like the native
languages of devices. This language is called MSIL, Microsoft Intermediate Language. We compile each
language to MSIL. During runtime the CLR uses a JIT (Just In Time) compiler to compile the MSIL code to
the native code for the device used.[3]
This requires one JIT compiler for each device to translate MSIL code
to the native code for that device. This translation process is not as difficult as translating a high-level
language to native code, because the MSIL code is similar to native code.
Figure 1.5: Compiling using an intermediate language
Moreover, using MSIL greatly reduces the number of compilers we need. For 10 languages and 10 devices,
we need one compiler for each language to translate it to MSIL, and one JIT compiler for each device to
translate MSIL code to native code for that device. Thus we need 20 compilers instead of 100. Figure 1.5
illustrates this approach.
The .NET Framework Class Library
The .NET Framework Class Library provides a large and very useful set of types that expedite the
development process. The library groups the types in namespaces that combine related types. It contains
about 100 namespaces of which we use only a small number in this text. Some of the namespaces from the
library that we use are:
System
Contains fundamental types
System.Collections
Defines various collections of objects
System.Data
Manages data from multiple sources including databases
System.Drawing
Provides graphics
System.IO
Allows reading and writing
System.Net
Provides an interface computers use to communicate over networks
System.Runtime.Remoting
Supports distributed applications
System.Text
Handles character encoding
System.Threading
Enables multithreaded programming
System.Web
Enables browser–server communication
System.Web.Services
Enables the building and use of web services
System.Windows.Forms
For user interfaces in Windows-based applications
System.Xml
Provides support for processing XML
The BIG Picture
The .NET Framework helps developers build applications for the diverse Internet environment. The Common
Language Runtime and .NET Framework Class Library provide services and types to make programmers
more productive.
Test Your Understanding
5. What do we call code that targets the Common Language
Runtime?
6. What are the two main parts of the .NET Framework?
Answers
5. managed code
[1]"Overview of the .NET Framework," from the .NET Framework Developer's Guide. See
http://msdn.microsoft.com/library/.
[2]Modern compilers use similar techniques to reduce the number needed to support multiple platforms.
[3]Java also uses a JIT compiler.
1.3 Overview of C#
History
FORTRAN and COBOL were among the first high-level languages, introduced in the late 1950s. Both are still
used today, FORTRAN for scientific applications and COBOL for business. Smalltalk, released around 1980,
is a fully object-oriented language that influenced its successors, including Java and C#.
Systems programmers who needed access to the machine hardware used assembly languages, which are
very low-level and specific to the hardware. The C language, developed in the mid 1970s, is sometimes
described as a portable assembly language. It is a high-level language, like FORTRAN and COBOL, but
provides access to machine hardware. The UNIX operating system, developed for the then-new
minicomputers, was mostly written in C, and both C and UNIX rapidly grew in popularity.
Although it is good for systems programming, C is a small language that does not facilitate the development
of large software systems. Introduced in the later 1960s, object-oriented programming started to become
popular in the mid 1980s. Languages that support object-oriented programming do facilitate the development
of large software systems. C++ extends C to include constructs that support object-oriented programming,
while still including those that access machine hardware. Consequently, C++ grew in popularity.
BASIC was developed in the 1960s as an easier way for students to learn to program. It used an interpreter
so students could immediately see the results of execution. Originally, personal computers had very limited
memory chips in which to hold programs, so BASIC, which did not require compilation to a larger low-level
representation, became the main language used on early PCs. As memory became cheaper and graphics
capabilities grew, BASIC morphed to Visual Basic, an extremely popular language for the rapid development
of user applications.
With the introduction of the .NET Framework, Visual Basic evolved to Visual Basic .NET, a cousin of C#. One
way we might describe C# is as a language that tries to combine the rapid application development of Visual
Basic with much of the power of C++.
With the rise of desktop computers and the rapid growth of the Internet in the mid 1990s came the need for a
language to support programming to enable users on vastly different systems to interact in a secure way.
Java, introduced in 1995, uses a Java Virtual Machine to provide security and enable programs developed on
different systems to interact. A large library extends its capabilities for Internet programming. Because it suited
the new demands on developers, Java has become very popular.
The goals of C# are similar to those of Java. Those versed in one of these languages can rapidly convert to
using the other. C# had the advantage of seeing the Java approach and how it might enhance it. C# adds
features for the easy development of components to make it easier for developers to combine programs
written on different systems. One can annotate a C# program with attributes that become part of the runtime
used by the CLR. This metadata describes the program so that other programs can use it. C#, newly
developed in the twenty-first century, promises to become very popular as the primary .NET programming
language.
C# Features
Microsoft[4]
identifies C# as a modern object-oriented language that allows programmers to quickly build
.NET components from high-level business objects to system-level applications. These components can
easily be converted to web services to be used over the Internet. Important characteristics are:
Productivity and safety: C# uses the .NET platform supporting web technologies. C# works well with XML,
the emerging standard to pass structured data over the Internet.
The C# design eliminates many costly programming errors. It includes automatic memory management
and initialization of variables. It checks types to avoid runtime errors.
C# reduces updating costs by supporting versioning in the language, making it easier and less costly to
introduce new versions of a product.
Power, expressiveness, and flexibility: C# allows a close connection between the abstract business
process and its software implementation. The developer can associate metadata with a program that will
allow tools to determine that a component is correctly identified as part of a business object or to create
reports.
To avoid the need to use C++ to access basic machine functions, C# permits carefully identified low-level
access to machine resources.
How C# Works
C# uses a compiler, but does not immediately translate a high-level program to the machine instructions of
each specific processor. The C# compiler takes as input the high-level C# program and outputs an equivalent
program written using the Microsoft Intermediate Language. During runtime the CLR uses a JIT compiler to
translate the MSIL code to the instruction set of the processor. Figure 1.6 shows the compilation of a C#
program to MSIL followed by the JIT compilation to native code on two different processors.
Figure 1.6: Compiling a C# program
The advantage of producing MSIL code instead of code for each different processor is that the same
intermediate code will run on any processor that has a CLR. We can download a C# program which has
been compiled to intermediate code on one type of machine and run it on a much different type of machine.
For networking, this feature of C# is invaluable.
In December, 2001 ECMA (European Computer Manufacturers Association, a body that promulgates
information technology standards) released the ECMA-334 standard for C#.
The BIG Picture
C# was created in the twenty-first century, basing much syntax on C and C++ and using concepts from
several other languages. It combines the rapid productivity of Visual Basic with the power of C++.
C# source compiles to intermediate code. The CLR uses a JIT compiler to translate the intermediate code to
code for the processor used. The .NET Framework makes C# very useful for Internet applications in which
diverse machines communicate.
Test Your Understanding