1. Trang chủ
  2. » Công Nghệ Thông Tin

The 10 Most Significant Differences between C# and C++

35 473 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề The 10 Most Significant Differences between C# and C++
Trường học Unknown University
Chuyên ngành Computer Science
Thể loại Essay
Năm xuất bản 2023
Thành phố Unknown City
Định dạng
Số trang 35
Dung lượng 546,15 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Chapter 17 The 10 Most Significant Differences between C# and C++In This Chapter No global data or functions All objects are allocated off of the heap Pointer variables are all but disal

Trang 1

Chapter 17 The 10 Most Significant Differences between C# and C++

In This Chapter

No global data or functions

All objects are allocated off of the heap

Pointer variables are all but disallowed

C# generics are like C++ templates — or are they?

I’ll never include a file again

Don’t construct — initialize

Define your variable types well

No multiple inheriting

Projecting a good interface

The unified type system

The C# language is more than a little bit based on the C++ programming

language This is hardly surprising because Microsoft built Visual C++,the most successful hard-core programming language for the Windows envi-ronment All of your best geeks were working in Visual C++ But C++ has beenshowing its age for a while now

However, C# is not just a coat of paint over a rusty language C# offers ous improvements, both by adding features and by replacing good featureswith better ones This chapter focuses on the Top Ten best improvements Ofcourse, I could easily make this the Top 20

numer-You may have arrived at C# from a different direction, such as Java or VisualBasic C# bears an even stronger resemblance to Java than to C++ — not surprising, because Java also arose partly to improve on C++ and is highlyInternet oriented You find syntactic differences, but C# and Java almost feellike clones If you can read one, you can read the other

As for Visual Basic — that is, Visual Basic NET, not the older Visual Basic 6.0 —its syntax is completely different, of course, but Visual Basic NET rests onthe same NET Framework infrastructure as C#, produces almost identicalCommon Intermediate Language code, and is highly interoperable with C#:

Trang 2

A C# class can inherit from a Visual Basic class and vice versa, and your gram can be a mixture of C# and Visual Basic modules (and, for that matter,

pro-“managed” C++ and J# and )

No Global Data or Functions

C++ passes itself off as an object-oriented language, and it is, in the sense thatyou can program in an object-oriented fashion using C++ You can also side-step class objects by just throwing data and functions out there in someglobal space, open to the elements and any programmer with a keyboard

C# makes its programmers declare their allegiance: All functions and all datamembers must join a class You want to access that function or data? Youhave to go through the author of that class — no exceptions

All Objects Are Allocated Off the Heap

C/C++ allows memory to be allocated in the following ways, each with its owndisadvantages:

 Global objects exist throughout the life of the program A program can

easily allocate multiple pointers to the same global object Change one,

and they all change, whether they’re ready or not A pointer is a variablethat contains the address of some distant chunk of memory Technically,C# references are pointers under the hood

 Stack objects are unique to individual functions (that’s good), but they are deallocated when the function returns Any pointer to a deallo-

cated memory object becomes invalid That would be fine if anyone toldthe pointer; however, the pointer still thinks it’s pointing to a validobject, and so does its programmer The C++ stack is a different region ofmemory from the heap, and it really is a stack

 Heap objects are allocated as needed These objects are unique to a

particular execution thread

The problem is that it’s too easy to forget what type of memory a pointerrefers to Heap objects must be returned when you’re done with them Forget

to do so, and your program progressively “leaks” memory until it can nolonger function On the other hand, if you release the same block of heapmore than once and “return” a block of global or stack memory, your pro-gram is headed for a long nap — maybe Ctrl+Alt+Del can wake it up

C# solves this problem by allocating all objects off of the heap Even betterthan that, C# uses garbage collection to return memory to the heap for you

No more blue screen of death haunts you because you sent the wrongmemory block to the heap

Trang 3

Pointer Variables Are All but Disallowed

The introduction of pointers to C ensured the success of that language

Pointer manipulation was a powerful feature Old-hand machine-languageprogrammers could still pull the programming shenanigans they were used

to C++ retained the pointer and heap features from C without modification

Unfortunately, neither the programmer nor the program can differentiate agood pointer from a bad one Read memory from an uninitialized pointer, andyour program crashes — if you’re lucky If you’re not lucky, the program cranksright along, treating some random block of memory as if it were a valid object

Pointer problems are often difficult to pin down An invalid pointer programusually reacts differently every time you run it

Fortunately for all concerned, C# manages to sidestep pointer problems bydoing away with them The references that it uses instead are type-safe andcannot be manipulated by the user into something that can kill the program

C# Generics Are Like C++ Templates —

or Are They?

If you look at C#’s new generics feature (see Chapter 15) beside C++’s plate feature, the syntax looks very similar However, although the two havethe same basic purpose, their resemblance is only skin deep

tem-Both generics and templates are type-safe, but under the hood they areimplemented very differently Templates are instantiated at compile time,while generic instantiation happens at run time This means the same tem-plate in two different NET assemblies results in two separate types that getinstantiated at compile time But the same generic in two different NETassemblies results in only one type that gets instantiated at run time The upside of this is less “code bloat” for generics than for templates

The biggest difference between generics and templates is that generics workacross multiple languages, including Visual Basic, C++, and other NET lan-guages, as well as C# Templates are purely a C++ feature

Which one is better? Templates are more powerful — and complex, like a lot

of things in C++ — but a great deal more error-prone — again, like a lot ofthings in C++ Generics are thus easier to use and less likely to result in abullet to your big toe

381

Chapter 17: The 10 Most Significant Differences between C# and C++

Trang 4

Of course, I’m only scratching the surface of this discussion here For a muchmore technical comparison, see Brandon Bray’s blog at weblogs.asp.net/branbray/archive/2003/11/19/51023.aspx.

I’ll Never Include a File Again

C++ enforces strict type checking — that’s a good thing It does so by

com-pelling you to declare your functions and classes in so-called include files,

which are then used by modules However, getting all the include files set up

in just the right order for your module to compile can get complicated

C# does away with that nonsense Instead, C# searches out and finds theclass definitions on its own If you invoke a Studentclass, C# finds the classdefinition on its own to make sure that you’re using it properly

Don’t Construct — Initialize

I could see the usefulness of constructors the first time I laid eyes on them.Provide a special function to make sure that all the data members were set

up correctly? What an idea! The only problem is that I ended up adding trivialconstructors for every class I wrote Consider the following example:

public class Account{

private double balance;

private int numChecksProcessed;

private CheckBook checkBook;

public Account(){

balance = 0.0;

numChecksProcessed = 0;

checkBook = new CheckBook();

}}

Why can’t I just initialize the data members directly and let the language ate the constructor for me? C++ asked why; C# answers why not? C# does awaywith unnecessary constructors by allowing direct initialization, as follows:

gener-public class Account{

private double balance = 0.0;

private int numChecksProcessed = 0;

private CheckBook checkBook = new CheckBook();

// no need to do this again in a constructor

Trang 5

More than that, if all you need is the appropriate version of zero for a lar type, as in the first two data members above, C# takes care of it for youautomatically, at least for class data members If you want something otherthan zero, add your own initialization right at the data member’s declaration.

particu-(Always initialize local variables inside functions, however.)

Define Your Variable Types Well

C++ is very politically correct It doesn’t want to step on any computer’s toes

by requiring that a particular type of variable be limited to any particular range

of values It specifies that an intis about “so big” and a longis “bigger.” Thisindecisiveness leads to obscure errors when trying to move a program fromone type of processor to another

C# doesn’t beat around the bush It says, an intis 32 bits and a longis 64bits, and that’s the way it’s going to be As a programmer, you can take thatinformation to the bank without unexpected errors popping up

No Multiple Inheriting

C++ allows a single class to inherit from more than one base class For ple, a SleeperSofacan inherit from both class Bedand class Sofa (But didyou ever try to sleep on one of those furniture hybrids with a torture rackjust under the thin mattress?) Inheriting from both classes sounds reallyneat, and in fact, it can be very useful The only problem is that inheritingfrom multiple base classes can cause some of the most difficult-to-find pro-gramming problems in the business

exam-C# drops back and avoids the increased number of errors by taking multipleinheritance away However, that wouldn’t have been possible had C# notreplaced multiple inheritance with a new feature: the interface, discussed inthe next section

Projecting a Good Interface

When people stepped back and looked at the multiple inheritance nightmarethat they had gotten themselves into, they realized that over 90 percent of the

time, the second base class existed merely to describe the subclass For

exam-ple, a perfectly ordinary class might inherit an abstract class Persistablewith abstract methods read()and write() This forced the subclass toimplement the read()and write()methods and told the rest of the worldthat those methods were available for use

383

Chapter 17: The 10 Most Significant Differences between C# and C++

Trang 6

Programmers then realized that the more-lightweight interface could do thesame thing A class that implements an interface like the following example ispromising that it provides the read()and write()capability:

interface IPersistable{

reap-Unified Type System

The C++ class is a nice feature It allows data and its associated functions to

be bundled into neat little packages that just happen to mimic the way thatpeople think of things in the world The only problem is that any languagemust provide room for simple variable types like integer and floating pointnumbers This need resulted in a caste system Class objects lived on oneside of the tracks, while value-type variables like intand floatlived on theother Sure, value types and object types were allowed to play in the sameprogram, but the programmer had to keep them separate in his mind

C# breaks down the Berlin Wall that divides value types from object types For

every value type, there is a corresponding “value type class” called a structure.

(You can write your own custom structure types too See Chapter 14.) Theselow-cost structures can mix freely with class objects, enabling the program-mer to make statements like the following:

MyClass myObject = new MyClass();

Console.WriteLine(myObject.ToString());// display a “myObject” in string formatint i = 5;

Console.WriteLine(i.ToString()); // display an int in string formatConsole.WriteLine(5.ToString()); // display the constant 5 in string format

Not only can I invoke the same method on intas I do on a MyClassobject,but I can also do it to a constant like 5 This scandalous mixing of variabletypes is a powerful feature of C#

Trang 7

Appendix About the CD

In This Appendix

System requirements

Using the CD with Windows

What you’ll find on the CD

Troubleshooting

The CD-ROM that comes tucked away inside the back cover of C# 2005 For

Dummies contains lots of goodies First, you’ll find the source code from

the numerous program examples you find throughout the book In addition,I’ve included five bonus chapters and three utility programs that can makeyour life as a programmer easier However, your machine must meet a fewminimum system requirements before you can make use of them

System Requirements

Parts of this book assume that you have Microsoft Visual Studio 2005 orMicrosoft Visual C# 2005, which is the preferred way to program with C#.However, if you don’t, you can use the free, open-source SharpDevelop pro-gram provided on the CD to build and run the book’s examples See BonusChapter 5 on the CD for information about SharpDevelop and about other waysyou can use this book cheaply Visual Studio is not supplied with this book

If you’re using Visual Studio, the hardware requirements for using the CD thatcomes with this book are the same as those for Visual Studio Refer to theVisual Studio System Requirements for details Make sure that your computermeets these minimum system requirements:

 A PC with a 600 MHz Pentium or faster processor, 1 GHz recommended

 Microsoft Windows XP, Service Pack 2 (Home or Professional); Windows

2000, Service Pack 4; or Windows 2003 Server

 At least 128MB of total RAM installed on your computer; for best mance, I recommend at least 256MB Visual Studio has a large appetitefor memory

Trang 8

perfor- At least 1MB of hard drive space, without installing MSDN tion to the hard drive, about 2MB if you do install the documentation (ifnot, you can use it from the Visual Studio CD), plus about 2MB if youinstall the book’s example programs

If you need more information on the basics, check out these books published

by Wiley Publishing, Inc.: PCs For Dummies, by Dan Gookin; Windows 2000

Professional For Dummies and Windows XP For Dummies, 2nd Edition, both by

Andy Rathbone; and Windows Server 2003 For Dummies, by Ed Tittel and

James Michael Stewart

Using the CD

To install the items from the CD to your hard drive, follow these steps:

1 Install Visual Studio 2005 or Visual C# 2005 if you have one of them,

or install SharpDevelop and/or TextPad as described in Step 5.

Follow the installation directions provided by the software vendor

2 Insert the book’s CD into your computer’s CD-ROM drive The license agreement appears.

Note to Windows users: The interface won’t launch if you have autorundisabled In that case, choose Start➪Run In the dialog box that appears,

type D:\start.exe (Replace D with the proper letter if your CD-ROM

drive uses a different letter If you don’t know the letter, see how yourCD-ROM drive is listed under My Computer.) Click OK

3 Read through the license agreement, and then click the Accept button

if you want to use the CD After you click Accept, the License Agreement window won’t appear again.

The CD interface appears The interface allows you to install the grams with just a click of a button (or two)

Trang 9

pro-4 To make life easiest, install the example programs You’ll want to refer

to them frequently Simply click the install button from the Code tion of the CD-ROM interface.

sec-You could refer to the examples by inserting the CD as needed, but havingthe programs on your hard drive is handiest They take up about 2MB ofdisk space

I provide all the necessary files to let you run the programs right out ofthe box That’s fine, but C# will come easier if you type in the code your-self, in a fresh Visual Studio project, rather than simply copying the pro-vided source files

The programs are in a folder called C:\C#Programs(no space) Thatlocation makes the file paths you see as you work with the files the same

as I describe in the book

When you create a project and give it a name, Visual Studio (orSharpDevelop) creates a folder of the same name

5 Install the bonus software that you want Just click the button from the Software menu of the CD-ROM interface to launch the installer and follow the on-screen prompts.

If you have Visual Studio or Visual C#, you won’t really needSharpDevelop But you’ll find TextPad and NUnit useful in any case

Follow the software vendor’s installation instructions

What You’ll Find on the CD

The following sections are arranged by category and provide a summary ofthe software and other goodies you’ll find on the CD If you need help withinstalling the items provided on the CD, refer to the installation instructions

in the preceding section

The C# programs

The first thing you’ll find on the CD are the C# source files for the programsfrom throughout this book These source files (with accompanying VisualStudio project and solution files) are organized into directories by programname Each directory contains all the files that go with a single example program

387

Appendix: About the CD

Trang 10

All the examples provided in this book are located in the C#Programstory on the CD and work with Windows 2000, 2003 Server, XP, and later com-puters These files contain much of the sample code from the book Thestructure of the examples directory is

direc-C:\C#Programs\ExampleProgram1C:\C#Programs\ExampleProgram2

Five bonus chapters

The C# 2005 For Dummies CD also includes five bonus chapters that

supple-ment the book’s text

 Bonus Chapter 1 explains how to do error handling in C# with C#

exceptions

 Bonus Chapter 2 explains how to read and write files from your C# programs

 Bonus Chapter 3 explains several ways to iterate collections of data

objects in C# — step through the objects one by one — including lines

in a text file The chapter includes the new iterator blocks from C# 2.0.

 Bonus Chapter 4 explains how to use the Visual Studio 2005 interface,including the debugger and the Help system

 Bonus Chapter 5 presents several ways to program cheaply in C# out Visual Studio, including the SharpDevelop and TextPad programsprovided on the CD

with-The CD also includes three bonus utility programs to help you program in C#

Shareware programs are fully functional, free, trial versions of copyrighted

programs If you like particular programs, register with their authors for anominal fee and receive licenses, enhanced versions, and technical support

Freeware programs are free, copyrighted games, applications, and utilities.

You can copy them to as many PCs as you like — for free — but they offer notechnical support

GNU software is governed by its own license, which is included inside the

folder of the GNU software There are no restrictions on distribution of GNUsoftware See the GNU license at the root of the CD for more details

Trial, demo, or evaluation versions of software are usually limited either by

time or functionality (such as not letting you save a project after you create it)

Trang 11

A program testing tool from www.nunit.org GNU open-source software ForWindows (also available for Mono on Unix/Linux/Mac machines, althoughthat version is not covered in this book)

Use NUnit, the most popular C# unit testing tool, to automate unit tests foryour code Unit tests test your classes and methods Bonus Chapter 5 on the

CD explains how to use NUnit

capa-in Visual Studio 2005, you can use it to program with the latest version of C#,version 2.0 I don’t recommend it for serious commercial software develop-ment, but it works fine with all the example programs in this book

TextPad

A programmer-oriented text editor from www.textpad.com Shareware trialversion, no trial duration specified For Windows 95, 98, ME, NT4, 2000,Server 2003, XP

If you lack Visual Studio 2005 — and SharpDevelop, described earlier, is not

to your taste — you may want to try using the popular TextPad code editor

as the center of your C# programming It’s a more rugged environment thanVisual Studio or SharpDevelop, but it’s cheap and surprisingly powerful Inany case, it’s a far better tool for programmers than Notepad Bonus Chapter

5 on the CD explains how to configure TextPad for C#

Troubleshooting

I tried my best to compile programs that work on most computers with theminimum system requirements Alas, your computer may differ, and someprograms may not work properly for some reason, or work only slowly

389

Appendix: About the CD

Trang 12

The most likely problem is that you do not have the Microsoft NET ment installed Programs created in C# require a set of NET libraries, whichyou must have installed on your computer Some versions of Windows maynow come with these libraries preinstalled If you have Visual Studio 2005

environ-or Visual C# Express 2005 installed, you definitely have the right libraries.(Older versions of Visual Studio don’t come with the latest version 2.0 ofthe NET libraries.) Otherwise, you can download or order the libraries fromwww.microsoft.com You want the NET SDK, version 2.0 Bonus Chapter 5

on the CD discusses in more detail how to obtain them

Another possible problem is that your computer does not have enoughmemory (RAM) If you get an error message such as Not enough memoryorSetup cannot continue, try one or more of the following suggestions andthen try using the software again:

 Turn off any antivirus software running on your computer Installation

programs sometimes mimic virus activity and may make your computerincorrectly believe that it’s being infected by a virus Trust me, it isn’t

 Close all running programs The more programs you have running, the

less memory is available to other programs Installation programs cally update files and programs; so if you keep other programs running,installation may not work properly

typi- Have your local computer store add more RAM to your computer This

is, admittedly, a drastic and somewhat expensive step, though not that

expensive nowadays However, adding more memory can really helpthe speed of your computer and allow more programs to run at thesame time

If you have trouble with the CD-ROM, please call the Wiley Product TechnicalSupport phone number at (800) 762-2974 Outside the United States, call1(317) 572-3994 You can also contact Wiley Product Technical Support athttp://www.wiley.com/techsupport John Wiley & Sons will provide technical support only for installation and other general quality controlitems For technical support on the applications themselves, consult the program’s vendor or author You can also check out a list of common prob-lems on the Web site of one of the authors at www.chucksphar.com

To place additional orders or to request information about other Wiley ucts, please call (877) 762-2974

Trang 13

& (ampersand) operator, 65

&& (double ampersand)operator, 65–66

* (asterisk)

as arithmetic operator, 57

in Forms Designer window, 24

\ (backslash), specialcharacters and, 95{} (braces)

class name and, 102–103using for clarity, 72[] (brackets)array and, 112

as index operator, CD76} (close brace) expectederror message, 377

= (equals) sign

as assignment operator,

40, 60–61reference types and,107–108

! (exclamation point)operator, 65

^ (exclusive or—xor)operator, 65// (forward slashes), 34

- (minus) sign and coderegion, 31

% (modulo) operator, 58,CD60

| (pipe) operator, 65

|| (double pipe) operator, 66+ (plus) operator and strings, 52+ (plus) sign and coderegion, 31

<T>and generic collectionsand, 338

abstraction See also abstract

classclass factoring, 288–293overview of, 213–215, 288AcceptButton property, 24access control

accessor methods, 226–227, 231containment and, 258–259DoubleBankAccountprogram example,227–230

importance of, 225–226overview of, 218–219,221–224

security, levels of, 224–225accessing

collection, CD72–CD74current object, 169–176member of object, 104–106project properties, 160–161static member of class, 110alignment guides, 22AlignOutputprogram,201–203

Alt+Tab (switch program),CD129

ampersand, double (&&)operator, 65–66ampersand (&) operator, 65

application See also console application; specific programs

action, adding, 25–27breaking, CD132–CD135building and running, 18–20console, creating, 29–31converting class into,CD114–CD115creating, 15description of, 12developing, CD142dividing into multipleassemblies, CD29–CD30dividing into multiplesource files, CD28–CD29executable, 12, 373executing, 19, 32, 35Forms Designer and, 20–24freeware, 388

rebuilding and running,24–25, 373–374running on differentmachines, CD180shareware, 388source files for example,387–388

template, creating, 15–18testing, 27–28

Application Wizard, 16, 17,CD32

approximation error, CD3argument

auto-complete feature and,178–179

implementing default,140–142

matching definitions withusage, 138–139

Index

Trang 14

argument (continued)multiple, passing tofunction, 136–138

as part of name of function,274–275

passing from DOS prompt,155–157

passing from Visual Studio

2005, 159–162passing from window,157–159

passing to default baseclass constructor,266–269

passing to function, 136value-type, passing byreference, 143–147value-type, passing byvalue, 142–143arithmetic operatorsassignment, 60–61increment, 61–62operating orders, 58–59overview of, 57

simple, 57–58array

argument for, 112description of, 101, 111–112disadvantages of, 334fixed-value, 112–114iterating through, 192Lengthproperty, 117linked list compared to,CD62

naming, 120objects and, 118–120sorting elements within,122–126

variable-length, 114–118ArrayListclass, 334,335–336

asoperator, 264–265, 337assembly, CD29–CD30assigning

expression type, 68–69multiple catch blocks,CD15–CD17assignment of reference, 126assignment operator (=)declaring variable and, 40math functions and, 60–61reference types and,107–108

asterisk (*)

as arithmetic operator, 57

in Forms Designer window, 24author, Web site of, 8, 390

“auto list members” Help,CD124–CD125auto-complete featuredisplaying, 26, 27documentation commentsand, 180–184

overview of, 176–177System Library and,177–179

for user-created functionsand methods, 179–180auto-indenting, 75

AverageAndDisplay()function, 137–138AverageAndDisplayOverloadedprogram,139–140

AverageStudentGPAprogram, 119–120AverageWithCompilerErrorprogram, 138avoiding

boxing and unboxing, 331confusion in code, 59, 60duplication amongconstructors, 245–248elsestatement, 76–77gotostatement, 98redundancy, 292tight coupling, 359

• B •

backslash (\) and specialcharacters, 95BankAccountclass,inheriting from, 254–257BankAccountprogram,222–224

BankAccountConstructorsAndFunctionprogram,245–247

BankAccountConstructorsAndThisprogram, 247–248

BankAccountWithMultipleConstructorsprogram, 243–245base class method,overloading, 275–280,374–375

base interface, 316basekeyword, 268–269,280–281

binary operator, 58bitwise operator, 65blank line, generating, 106bonus chapters, 388boolvariable, 49, 64–66boxing

nongeneric collections and,

336, 337value-type variable and,

149, 330–331braces ({})class name and, 102–103using for clarity, 72brackets ([])array and, 112

as index operator, CD76breakcommandlooping statements and,84–86

nested loop and, 93whileloop and, 86–89breaking

encapsulation, 279string, 203–205breakpoint, setting, 238, 239,CD132–CD135

browsing online help, 177bubble sort, 123–126buffer overwrite, CD72BuildASentenceprogram,190–192

building Windows Formsprogram, 18–20Button control, 22

• C •

C language, 61C++ programming languageconstructors and, 382–383global data or functionsand, 380

Trang 15

interface and, 383–384memory allocation and, 380multiple inheriting and, 383overview of, 379–380pointer variables and, 381template feature, 381–382type checking and, 382Unified Type System, 384variable types and, 383C# version 2.0

features of, 2overview of, 12–13resources on, 7–8, 177, 382CalculateInterestprogram, 73–74CalculateInterestTableprogram, 81–82, 129CalculateInterestTableMoreForgivingprogram, 86–87CalculateInterestTableWithFunctionsprogram, 130–132CalculateInterestWithEmbeddedTestprogram, 77–78calculating

interest, 73type of operation, 67–68call by reference feature,

147, 148–149Call Stack window,CD135–CD136calling initialization function, 233CAN_BE_USED_ASrelationshipoverview of, 303–305program example of,307–316

Cannot implicitly converttype ‘x’ into ‘y’ errormessage, 369–371cast

asoperator and, 264–265description of, 56invalid, 262–263protecting with isoperator, 263cast operator, 68, 69catch blocks, assigningmultiple, CD15–CD17

CD-ROMcontents of, 385, 387–389description of, 6

installing items to harddrive from, 386–387system requirements for,385–386

temperature conversionprogram, 44, 46troubleshooting, 389–390chaining assignments, 60changing type of variable,55–56

chapters, bonus, 388charvariable, 50–51, 53character

adding to or removing fromend of string, 201–203escaping, 95

newline, 106parsing out of string,194–196

replacing one with another,203–205

character types, 50–52

class See also Priority

Queueclassabstract, 293–296, 319access control and, 219,221–224

adding, CD110–CD111ArrayList, 334, 335–336BankAccount, inheritingfrom, 254–257

collection, writing own,CD61–CD71

concrete, 295Console, 160constdata member, 111containing another class,108–109

converting into program,CD114–CD115

CustomException, CD14declaring abstract, 319defining, 102–103description of, 101, 102, 233Dictionary, 335

Exception, creating own,CD13–CD15

Exception, overriding,CD22–CD26

factoring, 288–293, CD118FileStream, CD43–CD44functions and, 163generic, methods in,353–355

hierarchy of inherited, 266hierarchy, restarting,296–299

implementation of interfaceand, 305

inheritance and, 252–253instantiating locally, 249internal changes to, 230internalmember of, 225internal protectedmember of, 225LinkedList, 334methods and, 163name of, 102–103namespace and,CD33–CD35nongeneric collection,334–336

non-static member of, 128Object, 327, 328, 330object, 264

of object, changing, 261–262object of, 103–104

as part of name of function,274–275

partial, CD177–CD178protectedmember of, 225publicmember of,221–224, 225Queue, 334

as responsible for itself, 279sealing, 300, 375

Simple Factory, 358–359Stack, 335

static member of, 110StreamReader,CD50–CD54StreamWriter,CD45–CD50String, 187structure compared to, 327wrapper, 342

class constructor, 235–236class function, 128class inheritance, 219class library, CD27, CD29,CD39–CD43

393

Index

Trang 16

class method, 168class property, 110, 231–232,CD91

Class View, CD110classification, 215–217ClassLibraryprogram,CD40–CD41

‘className’ does notimplement interfacemember ‘methodName’

error message, 376

‘className.memberName’ isinaccessible due to it’sprotection level errormessage, 371–372Click event, setting, 25–26close brace (}) expectederror message, 377closed window, CD100closing program, 20CLR (Common LanguageRuntime), 3

codenavigating, CD110testing on differentmachines, CD180for Windows forms, writing,CD175–CD179

writing, CD115–CD119code region, 31

Code Snippets feature, 34–35Code view, 25

collection See also generic

collections

as alternative to array, 117description of, CD86–CD87directory of files, iteratingthrough, CD55–CD61index feature for,CD76–CD80iterating, CD72–CD75nongeneric, 334–336collection class, writing own,CD61–CD71

commandsbreak, 84–89, 93Console.Write(), 330continue, 84–86Readline(), 74ToDecimal(), 74WriteLine(), 74, 160

commentsdocumentation comments,180–184

reading, 129using, 34, CD117Common Language Runtime(CLR), 3

Community menu, CD124Compare()method, 189–193comparing floating pointnumbers, 47, 63–64compiler error, 336–337composing, 259compound assignmentoperators, 61compound logical operators,64–66

computational speed withdecimal variables, 49Concat()method, 204–205concept

class and, 102function and, 135concrete class, 295console applicationcomments in, 34core of, 34–35dropping file onto,

157, 158–159editing template file, 32–33executing by double-clicking, 157–158framework for, 33I/O and, CD43overview of, 29template, creating, 29–31testing, 31

Consoleclass, 160Console.Write()command, 330Console.WriteLinestatement, 34–35constdata member, 111constant

declaring, 79, 111numeric, declaring, 54–55stringconstant, 189writing, CD6

constraintgeneric method and, 356PriorityQueue()classand, 351–352

of type parameter, 362

constructoravoiding duplicationamong, 245–248C++ and, 382–383C#-provided, 233–234default, 235–237default base class, invoking,265–266

default, initializing objectdirectly and, 241–242default, passing arguments

to, 266–269default, program example,236–237

DemonstrateDefaultConstructorprogram,236–237

description of, 233, 234executing from debugger,238–241

initializing object directlyand, 241–242

overloading, 243–245parameters for, 362–364ConstructorSavingsAccountprogram,269–271

containersiterating through, 120–121linked list, CD61–CD71containment, 258–259continuecommand, 84–86control window, 21

controlling output manuallyFormat()method, 206–210overview of, 200–201Trim()and Pad()methods, 201–203controlling program flowforloop, 90–92foreachstatement,120–121

gotostatement, 98

ifstatement, 72–79nested loops, 92–95switchcontrol, 96–98whileloop, 80–90controls

events and, 25–27properties of, 23–24putting on form with codeonly, CD178–CD179working with, 21–22

Trang 17

Convertclass, 196, 198converting variable type,55–56

countingdecimal variable and, 49floating point variable and, 46

counting variable

in for loop, 92incrementing in whileloop, 83–84

CPU processor fault, 153Ctrl+C (interrupt runningprogram), CD56Ctrl+F5 (Start WithoutDebugging), 159Ctrl+K then Ctrl+X (viewmenu of snippets), 34Ctrl-Space (display auto-complete), 26current object, accessingoverview of, 169–171thiskeyword and, 171–176CustomExceptionclass,CD14

CustomExceptionprogram,CD23–CD26

• D •

data member, initializing, 172data, storing, 101

data structure, CD61Debug→Delete AllBreakpoints, CD134debugger

executing constructor from,238–241

SharpDevelop and,CD146–CD149debugging toolsbreakpoint, setting,CD132–CD135overview of, CD126single stepping,CD128–CD131stack trace, CD135–CD136Debug→Start Debugging, 159Debug→Start WithoutDebugging, 19, 159Debug→Step Into, 238Debug→Step Over, CD128

Debug→Windows→Breakpoints, CD134Debug→Windows→CallStack, CD135decimalvariable, 48–49DecimalBankAccountprogram, 228–230Decimal.Round()method,228–230

decimal.Round()statement, 83

decision-making See

controlling program flowdeclaration, 41

declared type, 283–284declaring

boolvariable, 49class abstract, 319constant, 79, 111decimalvariable, 48floating point variable,45–46

namespace, CD31–CD32numeric constant, 54–55variable, 40, 42, 319–320,

368, 369decrement operator, 62default constructorinitializing object directlyand, 241–242

invoking, 265–266overview of, 235–236passing arguments to,266–269

program example, 236–237default location for folder,changing, 18

definingclass, 102–103class properties, 231–232function with no value,152–153

method, 167–169static member function,165–167

variable type, 383delegating, 259DemonstrateDefaultConstructorprogram,236–237

demotion, 67–68dependency, 359

Dequeue()method, 342, 350destructor, 271–272

Dictionaryclass, 335directory

of files, iterating through,CD55–CD61

naming, 156discriminating betweenobjects, 106–107DisplayArgumentsprogram, 153–154displaying

auto-complete, 26line numbers,CD135–CD136, CD137project, CD108–CD110zero, trailing, 83DisplayRatio()function,152–153

DisplayRoundedDecimal()function, 141DisplayWithNestedLoopsprogram, 93–94

distributed development, 13dividing program

into multiple assemblies,CD29–CD30

into multiple source files,CD28–CD29

.DLLfile extension, CD29docked window, CD102Document Explorer, CD119document window, 21documentation comments,180–184

DOS command lineexecuting program from, 32passing argument from,155–157

DOS window, opening, 33dot operator, 107–108DotGNU Portable NETimplementation, 1double ampersand (&&)operator, 65–66double pipe (||) operator, 66doublevariable, 45

DoubleBankAccountprogram, 227–230do whileloop, 84down conversion, 68

395

Index

Ngày đăng: 04/10/2013, 21:20

TỪ KHÓA LIÊN QUAN

TÀI LIỆU CÙNG NGƯỜI DÙNG

TÀI LIỆU LIÊN QUAN

w