100% found this document useful (2 votes)
271 views

Instant Access to (eBook PDF) Microsoft Visual C#: An Introduction to Object-Oriented Programming 7th Edition ebook Full Chapters

Programming

Uploaded by

arusooesmati
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
271 views

Instant Access to (eBook PDF) Microsoft Visual C#: An Introduction to Object-Oriented Programming 7th Edition ebook Full Chapters

Programming

Uploaded by

arusooesmati
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

Download the full version of the ebook now at ebooksecure.

com

(eBook PDF) Microsoft Visual C#: An


Introduction to Object-Oriented Programming
7th Edition

https://ebooksecure.com/product/ebook-pdf-
microsoft-visual-c-an-introduction-to-object-
oriented-programming-7th-edition/

Explore and download more ebook at https://ebooksecure.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

C++ Programming: An Object-Oriented Approach, 1e ISE 1st


Edition Behrouz A. Forouzan - eBook PDF

https://ebooksecure.com/download/c-programming-an-object-oriented-
approach-1e-ise-ebook-pdf/

ebooksecure.com

(eBook PDF) Introduction to Programming Using Visual Basic


10th Edition

https://ebooksecure.com/product/ebook-pdf-introduction-to-programming-
using-visual-basic-10th-edition/

ebooksecure.com

Clearly Visual Basic: Programming with Microsoft Visual


Basic 2010, Second Edition Diane Zak - eBook PDF

https://ebooksecure.com/download/clearly-visual-basic-programming-
with-microsoft-visual-basic-2010-second-edition-ebook-pdf/

ebooksecure.com

(eBook PDF) Marketing 2016 18th Edition by William M.


Pride

https://ebooksecure.com/product/ebook-pdf-marketing-2016-18th-edition-
by-william-m-pride/

ebooksecure.com
(eBook PDF) Cengage Advantage: American Foreign Policy and
Process 6th Edition

https://ebooksecure.com/product/ebook-pdf-cengage-advantage-american-
foreign-policy-and-process-6th-edition/

ebooksecure.com

(eBook PDF) Organic Chemistry 6th Edition

https://ebooksecure.com/product/ebook-pdf-organic-chemistry-6th-
edition/

ebooksecure.com

Basic & Clinical Pharmacology, 15th Edition Bertram G.


Katzung - eBook PDF

https://ebooksecure.com/download/basic-clinical-pharmacology-15th-
edition-ebook-pdf/

ebooksecure.com

Ethics: Discovering Right and Wrong 8th Edition Louis P.


Pojman - eBook PDF

https://ebooksecure.com/download/ethics-discovering-right-and-wrong-
ebook-pdf/

ebooksecure.com

(eBook PDF) Fundamentals of Corporate Finance 13th Edition

https://ebooksecure.com/product/ebook-pdf-fundamentals-of-corporate-
finance-13th-edition/

ebooksecure.com
(eBook PDF) Data Analysis and Decision Making 4th Edition

https://ebooksecure.com/product/ebook-pdf-data-analysis-and-decision-
making-4th-edition/

ebooksecure.com
Joyce Farrell

Joyce Farrell
Microsoft Visual C# 2017
An Introduction to Object-Oriented Programming
Microsoft®

®
Visual C# 2017
An Introduction to
Object-Oriented Programming

To register or access your online learning solution or purchase materials


for your course, visit www.cengagebrain.com.
Seventh
Edition

Seventh Edition
Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203


Using the bool Data Type . . . . . . . . . . . . . . . . . 68


Understanding Numeric Type Conversion . . . . . . . . . . . 71
Using the char Data Type . . . . . . . . . . . . . . . . . 74
Using the string Data Type . . . . . . . . . . . . . . . . 76
vii
Defining Named Constants . . . . . . . . . . . . . . . . . 80
Working with Enumerations . . . . . . . . . . . . . . . . 81
Accepting Console Input . . . . . . . . . . . . . . . . . . 84
Using the Convert Class . . . . . . . . . . . . . . . . . 84
Using the Parse() Methods . . . . . . . . . . . . . . . 86
Chapter Summary . . . . . . . . . . . . . . . . . . . . . 89
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . . 90
Review Questions . . . . . . . . . . . . . . . . . . . . . 93
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . 96

CHAPTE R 3 Using GUI Objects and the Visual Studio IDE . . . 99


Creating a Form in the IDE . . . . . . . . . . . . . . . . 100
Using the Toolbox to Add a Button to a Form . . . . . . . 105
Adding Functionality to a Button on a Form . . . . . . . . 107
Adding Labels and TextBoxes to a Form . . . . . . . . 109
Understanding Focus and Tab Control . . . . . . . . . . 112
Formatting Data in GUI Applications . . . . . . . . . . . 113
Changing a Label’s Font . . . . . . . . . . . . . . . . 114
Naming Forms and Controls . . . . . . . . . . . . . . 114
Correcting Errors . . . . . . . . . . . . . . . . . . . . 116
Deleting an Unwanted Event-Handling Method . . . . . . . 117
Failing to Close a Form Before Attempting
to Reexecute a Program . . . . . . . . . . . . . . . . 118
Using Visual Studio Help . . . . . . . . . . . . . . . . 118
Deciding Which Interface to Use . . . . . . . . . . . . . . 119
Chapter Summary . . . . . . . . . . . . . . . . . . . . 125
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 126
Review Questions . . . . . . . . . . . . . . . . . . . . 127
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 130

CHAPTER 4 M ak in g Decis i o ns . . . . . . . . . . . . 133


Understanding Logic-Planning Tools and Decision Making . . 134
Making Decisions Using the if Statement . . . . . . . . . 137
A Note on Equivalency Comparisons . . . . . . . . . . . 143
Making Decisions Using the if-else Statement . . . . . . 145

Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
C o ntents Contents 

Using Compound Expressions in if Statements . . . . . . . 150


Using the Conditional AND Operator . . . . . . . . . . . 150
Using the Conditional OR Operator . . . . . . . . . . . . 152
Using the Logical AND and OR Operators . . . . . . . . . 153
viii Combining AND and OR Operators . . . . . . . . . . . . 154
Making Decisions Using the switch Statement . . . . . . . 159
Using an Enumeration with a switch Statement . . . . . . 162
Using the Conditional Operator . . . . . . . . . . . . . . 164
Using the NOT Operator . . . . . . . . . . . . . . . . . 165
Avoiding Common Errors When Making Decisions . . . . . . 167
Performing Accurate and Efficient Range Checks . . . . . 167
Using && and || Appropriately . . . . . . . . . . . . . . 169
Using the ! Operator Correctly . . . . . . . . . . . . . . 169
Decision-Making Issues in GUI Programs . . . . . . . . . . 171
Chapter Summary . . . . . . . . . . . . . . . . . . . . 175
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 175
Review Questions . . . . . . . . . . . . . . . . . . . . 177
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 181

CHAP TER 5 Lo o pin g . . . . . . . . . . . . . . . . 185


Creating Loops with the while Statement . . . . . . . . . 186
Creating Loops with the for Statement . . . . . . . . . . 195
Creating Loops with the do Statement . . . . . . . . . . . 198
Using Nested Loops . . . . . . . . . . . . . . . . . . . 200
Accumulating Totals . . . . . . . . . . . . . . . . . . . 206
Improving Loop Performance . . . . . . . . . . . . . . . 208
Avoiding Unnecessary Operations . . . . . . . . . . . . 208
Considering the Order of Evaluation
of Short-Circuit Operators . . . . . . . . . . . . . . . 209
Employing Loop Fusion . . . . . . . . . . . . . . . . . 210
Using Prefix Incrementing Rather
Than Postfix Incrementing . . . . . . . . . . . . . . . 210
Looping Issues in GUI Programs . . . . . . . . . . . . . . 212
Chapter Summary . . . . . . . . . . . . . . . . . . . . 215
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 216
Review Questions . . . . . . . . . . . . . . . . . . . . 217
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 220

CHAP TER 6 U s in g A r r a y s . . . . . . . . . . . . . . 223


Declaring an Array and Assigning Values . . . . . . . . . . 224
Initializing an Array . . . . . . . . . . . . . . . . . . . 226

Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203


Accessing Array Elements . . . . . . . . . . . . . . . . . 228


Using the Length Property . . . . . . . . . . . . . . . 229
Using foreach . . . . . . . . . . . . . . . . . . . . 230
Searching an Array Using a Loop . . . . . . . . . . . . . 233
ix
Using a for Loop to Search an Array . . . . . . . . . . 234
Improving a Loop’s Efficiency . . . . . . . . . . . . . . 236
Using a while Loop to Search an Array . . . . . . . . . 237
Searching an Array for a Range Match . . . . . . . . . . 239
Using the BinarySearch(), Sort(),
and Reverse() Methods . . . . . . . . . . . . . . . . 241
Using the BinarySearch() Method . . . . . . . . . . 241
Using the Sort() Method . . . . . . . . . . . . . . . 243
Using the Reverse() Method . . . . . . . . . . . . . . 244
Using Multidimensional Arrays . . . . . . . . . . . . . . . 247
Using Jagged Arrays . . . . . . . . . . . . . . . . . . 251
Array Issues in GUI Programs . . . . . . . . . . . . . . . 253
Chapter Summary . . . . . . . . . . . . . . . . . . . . 255
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 255
Review Questions . . . . . . . . . . . . . . . . . . . . 256
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 259

CHAPTER 7 U s in g M et h o ds . . . . . . . . . . . . . . 265
Understanding Methods and Implementation Hiding . . . . . 266
Understanding Implementation Hiding . . . . . . . . . . . 267
Writing Methods with No Parameters
and No Return Value . . . . . . . . . . . . . . . . . . 268
An Introduction to Accessibility . . . . . . . . . . . . . 269
An Introduction to the Optional static Modifier . . . . . 270
An Introduction to Return Types . . . . . . . . . . . . . 271
Understanding the Method Identifier . . . . . . . . . . . 271
Placing a Method in a Class . . . . . . . . . . . . . . . 272
Declaring Variables and Constants in a Method . . . . . . 273
Writing Methods That Require a Single Argument . . . . . . 276
Writing Methods That Require Multiple Arguments . . . . . . 280
Writing Methods That Return a Value . . . . . . . . . . . . 282
Writing a Method That Returns a Boolean Value . . . . . . 284
Analyzing a Built-In Method . . . . . . . . . . . . . . . 285
Passing Array Values to a Method . . . . . . . . . . . . . 289
Passing a Single Array Element to a Method . . . . . . . 289
Passing an Array to a Method . . . . . . . . . . . . . . 290

Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
C o ntents Contents 

Alternate Ways to Write a Main() Method Header . . . . . 293


Writing a Main() Method with a Parameter List . . . . . . 293
Writing a Main() Method with an Integer Return Type . . . 294
Writing a Main() Method with public Access . . . . . . 294
x Issues Using Methods in GUI Programs . . . . . . . . . . . 295
Understanding Methods That Are Generated
Automatically in the Visual Environment . . . . . . . . . 295
Appreciating Scope in a GUI Program . . . . . . . . . . . 296
Creating Methods to be Nonstatic When Associated
with a Form . . . . . . . . . . . . . . . . . . . . . 296
Chapter Summary . . . . . . . . . . . . . . . . . . . . 297
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 298
Review Questions . . . . . . . . . . . . . . . . . . . . 300
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 303

CHAP TER 8 A dvan ced Met hod Concepts . . . . . . . . 307


An Overview of C#’s Parameter Types . . . . . . . . . . . 308
Using Mandatory Value Parameters . . . . . . . . . . . . 308
Passing Parameters by Reference . . . . . . . . . . . . . 310
Using a ref Parameter . . . . . . . . . . . . . . . . . 311
Using an out Parameter . . . . . . . . . . . . . . . . 312
Using an out Variable . . . . . . . . . . . . . . . . . 313
Deciding Between out and ref . . . . . . . . . . . . . 313
Using a Built-in Method That Has an out Parameter . . . . 314
Using Parameter Arrays . . . . . . . . . . . . . . . . . 316
Returning a Reference from a Method . . . . . . . . . . . 319
Overloading Methods . . . . . . . . . . . . . . . . . . . 322
Understanding Overload Resolution . . . . . . . . . . . . 326
Discovering Built-In Overloaded Methods . . . . . . . . . 327
Avoiding Ambiguous Methods . . . . . . . . . . . . . . . 330
Using Optional Parameters . . . . . . . . . . . . . . . . 332
Leaving Out Unnamed Arguments . . . . . . . . . . . . 334
Using Named Arguments . . . . . . . . . . . . . . . . 335
Advantages to Using Named Arguments . . . . . . . . . 336
Disadvantages to Using Named Arguments . . . . . . . . 337
Overload Resolution with Named
and Optional Arguments . . . . . . . . . . . . . . . . 339
Chapter Summary . . . . . . . . . . . . . . . . . . . . 341
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 341
Review Questions . . . . . . . . . . . . . . . . . . . . 342
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 346

Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203


CHAPTER 9 U s in g C las s es and Obj ects . . . . . . . . 351


Understanding Class Concepts . . . . . . . . . . . . . . 352
Creating a Class from Which Objects Can Be Instantiated . . 354
Creating Instance Variables and Methods . . . . . . . . . 355 xi
Creating Objects . . . . . . . . . . . . . . . . . . . . . 357
Passing Objects to Methods . . . . . . . . . . . . . . . 360
Creating Properties . . . . . . . . . . . . . . . . . . . . 361
Using Auto-Implemented Properties . . . . . . . . . . . . 365
More About public and private Access Modifiers . . . . 371
Understanding the this Reference . . . . . . . . . . . . 375
Understanding Constructors . . . . . . . . . . . . . . . . 378
Passing Parameters to Constructors . . . . . . . . . . . 379
Overloading Constructors . . . . . . . . . . . . . . . . 380
Using Constructor Initializers . . . . . . . . . . . . . . 382
Using the readonly Modifier in a Constructor . . . . . . 384
Using Object Initializers . . . . . . . . . . . . . . . . . . 386
Overloading Operators . . . . . . . . . . . . . . . . . . 390
Declaring an Array of Objects . . . . . . . . . . . . . . . 395
Using the Sort() and BinarySearch()
Methods with Arrays of Objects . . . . . . . . . . . . 396
Understanding Destructors . . . . . . . . . . . . . . . . 403
Understanding GUI Application Objects . . . . . . . . . . . 405
Chapter Summary . . . . . . . . . . . . . . . . . . . . 407
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 409
Review Questions . . . . . . . . . . . . . . . . . . . . 411
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 414

CHAPTER 10 In t ro du ct io n t o I nheri tance . . . . . . . . 421


Understanding Inheritance . . . . . . . . . . . . . . . . . 422
Understanding Inheritance Terminology . . . . . . . . . . 424
Extending Classes . . . . . . . . . . . . . . . . . . . . 426
Using the protected Access Specifier . . . . . . . . . . 432
Overriding Base Class Members . . . . . . . . . . . . . . 436
Accessing Base Class Methods and Properties
from a Derived Class . . . . . . . . . . . . . . . . . 439
Understanding Implicit Reference Conversions . . . . . . . 445
Using the Object Class . . . . . . . . . . . . . . . . . 446
Using the Object Class’s GetType() Method . . . . . . 448
Using the Object Class’s ToString() Method . . . . . 448
Using the Object Class’s Equals() Method . . . . . . 449
Using the Object Class’s GetHashCode() Method . . . 450
Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
C o ntents Contents 

Working with Base Class Constructors . . . . . . . . . . . 452


Using Base Class Constructors That Require Arguments . . 453
Creating and Using Abstract Classes . . . . . . . . . . . . 456
Creating and Using Interfaces . . . . . . . . . . . . . . . 460
xii Using Extension Methods . . . . . . . . . . . . . . . . . 465
Recognizing Inheritance in GUI Applications . . . . . . . . . 467
Chapter Summary . . . . . . . . . . . . . . . . . . . . 470
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 471
Review Questions . . . . . . . . . . . . . . . . . . . . 473
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 476

CHAP TER 11 E xcept io n Handl i ng . . . . . . . . . . . . 483


Understanding Exceptions . . . . . . . . . . . . . . . . . 484
Purposely Generating a SystemException . . . . . . . . 486
Comparing Traditional and Object-Oriented
Error-Handling Methods . . . . . . . . . . . . . . . . . 491
Understanding Object-Oriented
Exception-Handling Methods . . . . . . . . . . . . . . 492
Using the Exception Class’s ToString() Method
and Message Property . . . . . . . . . . . . . . . . . 496
Catching Multiple Exceptions . . . . . . . . . . . . . . . 501
Examining the Structure of the TryParse() Methods . . . 506
Using the finally Block . . . . . . . . . . . . . . . . 508
Handling Exceptions Thrown from Outside Methods . . . . . 511
Tracing Exception Objects Through the Call Stack . . . . 514
A Case Study: Using StackTrace . . . . . . . . . . . . 515
Creating Your Own Exception Classes . . . . . . . . . . 519
Rethrowing an Exception . . . . . . . . . . . . . . . . 523
Chapter Summary . . . . . . . . . . . . . . . . . . . . 525
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 526
Review Questions . . . . . . . . . . . . . . . . . . . . 527
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 531

CHAP TER 12 U s in g C o n t ro l s . . . . . . . . . . . . . . 535


Understanding Controls . . . . . . . . . . . . . . . . 536
Examining the IDE’s Automatically Generated Code . . . . . 541
Setting a Control’s Font . . . . . . . . . . . . . . . . 545
Using a LinkLabel . . . . . . . . . . . . . . . . . . . 548
Adding Color to a Form . . . . . . . . . . . . . . . . . . 552
Using CheckBox and RadioButton Objects . . . . . . . 559
Adding a PictureBox to a Form . . . . . . . . . . . . . 563

Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203


Adding ListBox, CheckedListBox,


and ComboBox Controls to a Form . . . . . . . . . . . . 566
Adding MonthCalendar and DateTimePicker
Controls to a Form . . . . . . . . . . . . . . . . . . . 571
xiii
Working with a Form’s Layout . . . . . . . . . . . . . . 575
Understanding GroupBoxes and Panels . . . . . . . . 577
Adding a MenuStrip to a Form . . . . . . . . . . . . . 578
Using Other Controls . . . . . . . . . . . . . . . . . . 580
Chapter Summary . . . . . . . . . . . . . . . . . . . . 590
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 591
Review Questions . . . . . . . . . . . . . . . . . . . . 591
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 594

CHAPTER 13 H an dlin g Eve nt s . . . . . . . . . . . . . 597


Event Handling . . . . . . . . . . . . . . . . . . . . . . 598
Understanding Delegates . . . . . . . . . . . . . . . . . 602
Creating Composed Delegates . . . . . . . . . . . . . . 605
Declaring and Using Both Custom
and Built-in Event Handlers . . . . . . . . . . . . . . . 611
Using the Built-in EventHandler . . . . . . . . . . . . 614
Handling Control Component Events . . . . . . . . . . . 621
Handling Mouse and Keyboard Events . . . . . . . . . . . 626
Handling Mouse Events . . . . . . . . . . . . . . . . . 626
Handling Keyboard Events . . . . . . . . . . . . . . . . 628
Managing Multiple Controls . . . . . . . . . . . . . . . 631
Defining Focus . . . . . . . . . . . . . . . . . . . . . 631
Handling Multiple Events with a Single Handler . . . . . . 632
Continuing to Learn about Controls and Events . . . . . . 633
Chapter Summary . . . . . . . . . . . . . . . . . . . . 636
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 637
Review Questions . . . . . . . . . . . . . . . . . . . . 638
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 641

CHAPTER 14 F iles an d St ream s . . . . . . . . . . . . 645


Files and the File and Directory Classes . . . . . . . . 646
Using the File and Directory Classes . . . . . . . . 648
Understanding File Data Organization . . . . . . . . . . . 652
Understanding Streams . . . . . . . . . . . . . . . . . . 654
Writing and Reading a Sequential Access File . . . . . . . . 658
Writing Data to a Sequential Access Text File . . . . . . . 658
Reading from a Sequential Access Text File . . . . . . . . 661
Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
C o ntents Contents 

Searching a Sequential Text File . . . . . . . . . . . . . . 667


Understanding Serialization and Deserialization . . . . . . . 673
Chapter Summary . . . . . . . . . . . . . . . . . . . . 686
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 687
xiv Review Questions . . . . . . . . . . . . . . . . . . . . 689
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 692

A ppen dix A Oper at o r P recedence and Associ ati v i ty . . . 695


Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 696

A ppen dix B U n der s t an di ng Numberi ng Sy stems


an d Co m put er Codes . . . . . . . . . . . 697
The Hexadecimal System . . . . . . . . . . . . . . . . . 703
Measuring Storage . . . . . . . . . . . . . . . . . . . . 704
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 706

A ppen dix C U s in g t h e I DE Edi tor . . . . . . . . . . . 707


IntelliSense . . . . . . . . . . . . . . . . . . . . . . . 707
Providing Completion Lists . . . . . . . . . . . . . . . . 707
Providing Quick Information . . . . . . . . . . . . . . . . 708
Providing Parameter Information . . . . . . . . . . . . . . 709
Adding using Statements . . . . . . . . . . . . . . . . 709
Code Snippets . . . . . . . . . . . . . . . . . . . . . . 709
Squiggles and Lightbulbs . . . . . . . . . . . . . . . . . 709
Readability Aids . . . . . . . . . . . . . . . . . . . . . 710
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 710

Glo s s ar y . . . . . . . . . . . . . . . . 711

In dex . . . . . . . . . . . . . . . . . . 729

Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
Preface
xv

Microsoft Visual C# 2017, Seventh Edition provides the beginning programmer with a guide to
developing programs in C#. C# is a language developed by the Microsoft Corporation as part
of the .NET Framework and Visual Studio platform. The .NET Framework contains a wealth
of libraries for developing applications for the Windows family of operating systems.
With C#, you can build small, reusable components that are well-suited to Web-based
programming applications. Although similar to Java and C++, many features of C# make it
easier to learn and ideal for the beginning programmer. You can program in C# using a simple
text editor and the command prompt, or you can manipulate program components using
Visual Studio’s sophisticated Integrated Development Environment. This book provides you
with the tools to use both techniques.
This textbook assumes that you have little or no programming experience. The writing is
nontechnical and emphasizes good programming practices. The examples are business
examples; they do not assume mathematical background beyond high school business math.
In addition, the examples illustrate one or two major points; they do not contain so many
features that you become lost following irrelevant and extraneous details. This book provides
you with a solid background in good object-oriented programming techniques and introduces
you to object-oriented terminology using clear, familiar language.

Organization and Coverage


Microsoft Visual C# 2017 presents C# programming concepts, enforcing good style, logical
thinking, and the object-oriented paradigm. Chapter 1 introduces you to the language by letting
you create working C# programs using both the simple command line and the Visual Studio
environment. In Chapter 2, you learn about data and how to input, store, and output data in C#.
Chapter 3 provides a quick start to creating GUI applications. You can take two approaches:
•• You can cover Chapter 3 and learn about GUI objects so that you can create more visually
interesting applications in the subsequent chapters on decision making, looping, and array
manipulation. These subsequent chapters confine GUI examples to the end of the chapters,
so you can postpone GUI manipulation if you want.
•• You can skip Chapter 3 until you have learned the fundamentals of decision making,
looping, and array manipulation, and until you study object-oriented concepts such as
classes, objects, polymorphism, inheritance, and exception handling. Then, after Chapter
11, you can return to Chapter 3 and use the built-in GUI component classes with a deeper
understanding of how they work.

Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
Visit https://testbankfan.com
now to explore a rich
collection of testbank or
solution manual and enjoy
exciting offers!
P re f ace Organization and Coverage

In Chapters 4, 5, and 6, you learn about the classic programming structures—making decisions,
looping, and manipulating arrays—and how to implement them in C#. Chapters 7 and 8
provide a thorough study of methods, including passing parameters into and out of methods
and overloading them.
xvi Chapter 9 introduces the object-oriented concepts of classes, objects, data hiding, constructors,
and destructors. After completing Chapters 10 and 11, you will be thoroughly grounded in
the object-oriented concepts of inheritance and exception handling, and will be able to take
advantage of both features in your C# programs. Chapter 12 continues the discussion of GUI
objects from Chapter 3. You will learn about controls, how to set their properties, and how to
make attractive, useful, graphical, and interactive programs. Chapter 13 takes you further into
the intricacies of handling events in your interactive GUI programs. In Chapter 14, you learn to
save data to and retrieve data from files.

Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
Features
This text focuses on helping students become better programmers and
understand C # program development through a variety of key
features. In addition to chapter Objectives, Summaries, and Key Terms,
these useful features will help students regardless of their learning styles.
xvii

CHAPTER 1
YOU DO IT follows each major
concept. Each “You Do It” section
walks students through program
You Do It
development step by step.
32 Compiling and Executing a Program from the Command Line
If you do not plan to use the command line to execute programs, you can skip to the next part of
this “You Do It” section: “Compiling and Executing a Program Using the Visual Studio IDE.”
CHAPTER 2 Using Data

When allinyou
1. Go to the command prompt on your system. For example, want to10,
Windows accomplish is to increase a variable’s value by 1, there is no apparent
start to type Developer Command Prompt in thedif ference
“Ask me between
anything”using the prefix and postfix increment operators. However, these operators
search
function differently. When you use the prefix 11, the result is calculated and stored and then
box, and then click the option.
the variable is used. For example, in the following code, both b and c end up holding 5. The
2. Change the current directory to the name of the folder that holdsstatement
WriteLine() your displays 5 and 5. In this example, 4 is assigned to b, then b becomes 5,
66
program. You can type cd\ and then press Enter toandreturn
thento5 the root to c.
is assigned
directory. You can then change the path to the one where
b = 4;your program
resides. For example, if you stored your program file
c in
= a++b;
folder named
Chapter01 within a folder named CSharp, then you WriteLine("{0}
can type the following:
and {1}", b, c);
cd CSharp\Chapter01 In contrast, when you use the postfix 11, the variable is used, and then the result is calculated
The command cd is short for change directory. and stored. For example, in the second line of the following code, 4 is assigned to c; then, after
the assignment, b is increased and takes the value 5.
3. Type the command that compiles your program:
b = 4;
csc Hello.cs c = b++;
WriteLine("{0} and {1}", b, c);
If you receive no error messages and the prompt returns, it means that the
compile operation was successful, that a file namedThisHello.exe has been statement displays 5 and 4. In other words, if b = 4, then the value of
last WriteLine()
created, and that you can execute the program. If you b++do receive
is also error
4, and, in the second statement above, that value is assigned to c. However, after the
messages, check every character of the program you 4 is typed
assigned to to c, b is
make increased to 5.
sure
NOTES provide additionalit matches Figure 1-9 in the last “You Do It” section. Remember, C#need
When you is case
to add 1 to a variable in a standalone statement, the results are the same whether you use
sensitive, so all casing must match exactly. When you have corrected theincrement operator. However, many programmers routinely use the postfix operator when
information—for example,errors, repeat this step to compile the program again.
a prefix or postfix
they could use either operator. This is probably a mistake because the prefix operator is more efficient. You

another location inverify


4. You can thethatbook will see an example that proves the superior efficiency of the prefix operator in the chapter “Looping.”
a file named Hello.exe was created in these ways:
Ap prefix or postfix decrement operator (––) reduces a variable’s value by 1. For example,
that expands•onAt the
a topic,
commandor prompt, type dir to view a directoryanoftthe
if s and are files
bothstored
assignedinthe value 34, then the expression --s has the value 33 and the
the current folder. Both Hello.cs and Hello.exe should appeart--inhas thethelist.
a common error for which expression
• Use Windows Explorer to view the contents of the folder in which you
value 34, but t then becomes 33.

to watch out. stored your program, verifying that two Hello files are listed.Watch the video Using Shortcut Arithmetic Operators.

(continues)
TWO TRUTHS & A LIE
Using Arithmetic Operators
1. The value of 26 % 4 * 3 is 18.
2. The value of 4 / 3 1 2 is 3.

VIDEO LESSONS help 3. If price is 4 and tax is 5, then the value of price – tax++ is –1.
explain important chapter
concepts. Videos are
26. Then 2 * 3 is 6.
of the expression, 26 % 4, is 2, because 2 is the remainder when 4 is divided into

available for student and


The false statement is #1. The value of 26 % 4 * 3 is 6. The value of the first part

instructor download at
CengageBrain.com.

Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
Feat u res

TWO TRUTHS & A LIE quizzes appear


after each chapter section, with answers
provided. The quiz contains three statements
based on the preceding section of text—two
statements are true and one is false.
xviii
Answers give immediate feedback without
“giving away” answers to the multiple-choice
questions and programming problems later
in the chapter.

CHAPTER 1

TWO TRUTHS & A LIE


Programming
4 Two of the following statements are true, and one is false. Identify the false statement, and
explain why it is false. Making Decisions Using the if Statement

1. A high-level programming language allows you to use a vocabulary of reasonable terms


such as read, write, or add instead of the
Insequence
the code of
in on/off
Figureswitches thatthere
4-3, notice perform
is no semicolon at the end of the line that contains
these tasks. if(number < 5). The statement does not end at that point; it ends after WriteLine("A");.
If you incorrectly insert a semicolon at the end of if(number < 5), then the code means,
2. Each high-level programming language has its own syntax.
“If number is less than 5, do nothing; then, no matter what the value of number is, display A.”
3. Programmers use a computer program Figure called a4-4
compiler
showsto translate
the machine
flowchart logic code
that matches the code when a semicolon is incorrectly
139
into a high-level language they can understand.
placed at the end of the if expression.

level language statements into machine code.


The false statement is #3. Programmers use a compiler to translate their high-
false true Notice the semicolon here. Even
number < 5 though the next line is indented,
it is not part of the if statement.
Procedural and Object-Oriented Programming
Two popular approaches to writing computer programs are procedural programming and
object-oriented programming.
When you write a procedural program, you use your knowledge about a programming if(number < 5);
language to create and name computer memory locations that can hold values, and you writeWriteLine("A");
a
write "A"
series of steps or operations to manipulate those values. For example, a simple payroll program
WriteLine("B");
might contain instructions similar to the following:
get hoursWorked
pay = hoursWorked * 10.00
output pay write "B"

Named computer memory locations that hold data, such as hoursWorked and pay, are called
variables because they hold values that might vary. In programming languages, a variable is
referenced by using a one-word name (an identifier) with no embedded spaces. For example,
Figure 4-4 Flowchart
the memory location referenced by the name hoursWorked and code
might contain includingvalues
different an if statement with a semicolon following the
at different times for different employees. During if expression
the execution of the payroll program, each
value stored under the name hoursWorked might have many operations performed on it—for
example, reading it from an input device, multiplying
Although it by
it isa customary,
pay rate, and
andprinting it onto
good style, paper.
indent any statement that executes when an if
Boolean expression evaluates as true, the C# compiler does not pay any attention to the
indentation.
Examples of procedural programming languages include C andEach
Logo.of the following if statements displays A when number is less than 5. The
first shows an if statement written on a single line; the second shows an if statement on two
lines but with no indentation. The third uses conventional indentation. All three examples
execute identically.
THE DON’T DO IT ICON illustrates
how NOT to do something—for if(number < 5) WriteLine("A");
if(number < 5)
example, having a dead code path inWriteLine("A");
Don’t Do It
if(number < 5) Although these first two formats work for

a program. This icon provides a visual WriteLine("A");


if statements, they are not conventional,
and using them makes a program harder
to understand.
jolt to the student, emphasizing that
particular figures are NOT to be
emulated and making students more
careful to recognize problems in
existing code.
Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
Assessment
PROGRAMMING EXERCISES provide
opportunities to practice concepts.
These exercises increase in difficulty
and allow students to explore each major xix
programming concept presented in the
chapter. Additional programming exercises
are available to instructors on the
Companion Site.

CHAPTER 1

Review Questions
1. Programming languages such as C#, Java, and Visual Basic are
_____________________ languages.

42 a. machine c. low-level
b. high-level C H A d.
P Tuninterpreted
ER 2 Using Data

2. A program that translates high-level programs into intermediate or machine code

a. mangler
Exercises
c. analyst
b. compactor d. compiler
Programming Exercises
3. The grammar and spelling rules of a programming language constitute its
96
_____________________. 1. What is the numeric value of each of the following expressions, as evaluated by the C#
programming language?
a. logic c. class
b. variables d. a.syntax
215*3 g. 64 % 8
b. 9 / 4 1 10 h. 5 1 2 * 4 – 3 * 4
4. Variables are _____________________ .
c. 10 / 3 i. 3 * (2 1 5) / 5
a. named memory locations c. grammar rules
d. 21 % 10 j. 28 % 5 – 2
b. unexpected results d. operations
e. (5 – 1) * 3 k. 19 / 2 / 2
5. Programs in which you create and use objects that have
f. 37attributes
/5 similar to their real- l. 28 / (2 1 4)
world counterparts are known as _____________________ programs.
2. What is the value of each of the following Boolean expressions?
a. procedural c. object-oriented
a. 5 > 4 f. 3 1 4 55 4 1 3
b. logical d. authentic
b. 3 <5 3 g. 1 !5 2
6. Which of the following pairs is an example of a class
c. and
2 1an4 object,
>5 in that order? h. 2 !5 2
a. University and Yale c. d.Clydesdale
6 55 7 and horse i. –5 55 7–2
b. Chair and desk d. e.Maple
2 1 4and
<5tree
6 j. 3 1 9 <5 0
7. The technique of packaging an object’s attributes
3. into a cohesive
Choose unit
the best that
data canfor
type beeach
usedof the following, so that no memory storage is
as an undivided entity is _____________________ .wasted. Give an example of a typical value that would be held by the variable, and
a. inheritance c. explain why you chose the type you did.
polymorphism
b. encapsulation d. a.interfacing
the number of years of school you have completed
b. your final grade in this class
8. Of the following languages, which is least similar to C#?
c. the population of China
a. Java c. C++
d. the number of passengers on an airline flight
b. Visual Basic d. machine language
e. one player’s score in a Scrabble game
f. the number of Electoral College votes received by a U.S. presidential candidate
g. the number of days with below freezing temperatures in a winter in Miami, Florida
h. one team’s score in a Major League Baseball game
REVIEW QUESTIONS test
4. In this chapter, you learned that although a double and a decimal both hold
student comprehension of the floating-point numbers, a double can hold a larger value. Write a C# program named
DoubleDecimalTest that declares and displays two variables—a double and a
major ideas and techniques decimal. Experiment by assigning the same constant value to each variable so that the
presented. Twenty questions assignment to the double is legal but the assignment to the decimal is not. In other
words, when you leave the decimal assignment statement in the program, an
follow each chapter.

Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
A ssess m ent

DEBUGGING EXERCISES are included


with each chapter because examining
programs critically and closely is a
crucial programming skill. Students
xx can download these exercises at
CHAPTER 1

CengageBrain.com. These files are


9. From 1925 through 1963, Burma Shave advertising signs appeared next to highways
also available
all across to There
the United States. instructors through
were always four or five signs in a row containing
sso.cengage.com
pieces of a rhyme, followed by a final sign that read “Burma Shave.” For example, one
set of signs that has been preserved by the Smithsonian Institution reads as follows:
46 Shaving brushes
You’ll soon see ’em
On a shelf
In some museum
Burma Shave
Find a classic Burma Shave rhyme on the Web and write a program named
BurmaShave that displays the rhyme.

Debugging Exercises
1. Each of the following files in the Chapter.01 folder of your downloadable student files
CASE PROBLEMS provide opportunities
has syntax and/or logical errors. In each case, determine the problem and fix the
program. After you correct the errors, save each file using the same filename preceded
to build more detailed programs that
with Fixed. For example, DebugOne1.cs will become FixedDebugOne1.cs.
a. DebugOne1.cs c. continue to incorporate increasing
DebugOne3.cs
b. DebugOne2.cs d. DebugOne4.cs
functionality throughout the book.
Case Problems

The case problems in this section introduce two fictional businesses. Throughout this
book, you will create increasingly complex classes for these businesses that use the newest
concepts you have mastered in each chapter.
1. Greenville County hosts the Greenville Idol competition each summer during the county
fair. The talent competition takes place over a three-day period during which contestants
are eliminated following rounds of performances until the year’s ultimate winner is chosen.
Write a program named GreenvilleMotto that displays the competition’s motto, which is
“The stars shine in Greenville.” Create a second program named GreenvilleMotto2 that
displays the motto surrounded by a border composed of asterisks.

2. Marshall’s Murals is a company that paints interior and exterior murals for both
business and residential customers. Write a program named MarshallsMotto that
displays the company motto, which is “Make your vision your view.” Create a second
program named MarshallsMotto2 that displays the motto surrounded by a border
composed of repeated Ms.

Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
Exploring the Variety of Random
Documents with Different Content
step.
Father.—Well, say two feet and a half to each step.
Ernest.—Twice 32 makes 64; the half of 32 is 16; which added to
64 makes 80 feet.
Father.—Very well. Tell me now, if you recollect the proper term in
geometry for the circumference of a circle, or say of a tree, since we
are talking of trees.
Ernest.—Oh, you may be sure that I could not forget that it is
called the periphery.
Father.—Right. And what is the term for any line which may be
drawn from one point of the periphery to another, passing through
the centre? Now, Jack, you may show us what a great geometrician
you intend to be.
Jack.—I believe it is called the diameter.
Father.—So far right. Next, can you tell me what is the diameter of
a periphery of eighty feet, and what distance there is between the
extremities of the roots of the giant tree and its trunk?
The boys all began to reckon, and soon one said one number, one
said another,—at random; but Fritz called out louder than the rest,
that the distance was twenty-six feet.
Father.—You are pretty near. Tell me, did you make a calculation,
or was it a mere guess?
Fritz.—No, father, not a guess; but I will tell you. In the town in
which we lived, I have often taken notice that the hatter, when he
was about to bind the edge of a hat, always measured three times
the length of the diameter, and a trifle over, for the quantity of ribbon
he should use: thus I had no difficulty in finding that the third of
eighty was about twenty-six; and adding a couple of feet for the over
measure, we may call it twenty-eight.
Father.—I am glad to see you did not lose such an opportunity for
calculation; but a great boy like you, who have advanced in your
studies, ought not to be under obligations to the hatter for the
answer. But now let us go back to the measure of our trees, which
are really of a most extraordinary size. Height from the ground to the
branches, sixty-six feet; thickness, eight feet in diameter, and twenty-
eight feet distance from the extremities of the roots to the trunk. They
really, with propriety, may be called giant trees.
Having finished our conversation, we performed our devotions,
and retired to rest, grateful and well satisfied to find ourselves once
more together, and in health. We soon closed our eyes, and enjoyed
tranquil slumbers till break of day.
CHAPTER VIII.
Construction of a bridge.

When my wife and I were awake next morning, we resumed the


question of our change of abode. I observed to her, that it was a
matter of great difficulty, and required mature consideration;
otherwise we might hereafter have reason to repent the useless
labour and inconvenience we should have brought upon ourselves,
by a fruitless removal. My own opinion is, said I, that, upon the
whole, we had better remain here, where Providence seems to have
conducted us; the situation of the place affords conveniences, both
with respect to our personal safety and being so near to the vessel,
from which we may continue to enrich ourselves. See how
completely we are on all sides protected by the rocks; it is an
asylum, inaccessible but by sea or by the passage of the river, which
is not easily accomplished. Let us then have patience yet a little
longer, at least, till we have got all that can be removed, or that
would be useful to us, from the ship.
Nothing can be sounder than your reasons, my love, replied my
wife; but indeed no patience can endure the intense heat of these
sands, which is even increased by the vicinity of the rocks. It is not
easy for you to conceive how great my sufferings are from this
cause; for you have generally been out on some voyage of
discovery, and have been occasionally relieved by the shade of
trees. Another consideration is, that by remaining here, we must
renounce all hope of procuring fruits of any kind, and must live on
oysters, to which we have all a great aversion, or on such wild birds
as that which you found so unpalatable. And, for the safety you
boast of, the rocks did not prevent our receiving a visit from the
jackalls; nor is it improbable that tigers or other animals might follow
their example. Lastly, in regard to the treasures we might continue to
draw from the vessel, I renounce them with all my heart. We are
already in possession of a great abundance of provisions and other
useful things; and, for my part, my heart is always filled with the most
distressing apprehensions, whenever you and Fritz are exposed to
the danger of that perfidious element the sea.
Upon my word, my love, the shade of your giant trees has inspired
you with a most powerful eloquence; and I perceive that nothing so
effectually animates the language of a female, as an ardent desire
and a fixed determination to carry a particular point; I see that the
affair will end by my submitting to your will. You are, as you ought to
be, the director of our plans; but let us have a well-digested scheme
of operation before we leave this spot for your favourite wood.—
First, we must contrive a place among the rocks, where we can
leave our provisions and other things, which may serve both for a
fortress and a storehouse, and to which, in case of any danger from
invasion in the wood, we can immediately retreat.—Come then, this
agreed, the next thing is to throw a bridge across the river, if we are
to pass it with all our family and baggage.
A bridge! exclaimed my wife; can you possibly think of such a
thing? If we stay while you build a bridge, we may consider
ourselves as fixt here for life. What reason can there be, that we
should not cross the river as we did before? The ass and the cow will
carry all our goods upon their backs.
But do you recollect, that to preserve dry what they carry, they
must not perform their journey as they did from the vessel? For this
reason, then, if for no other, we must contrive a bridge. We shall
want also some sacks and baskets to contain our different matters;
you may therefore set about making these, and I will undertake the
bridge, which the more I consider, the more I find to be of
indispensable necessity; for the stream will, no doubt, at times
increase, and the passage become impracticable in any other way.
At this very time it would be found so for our shortest-legged
animals, and I am sure you would not wish to see them drowned. But
even our own boys, at least the youngest, will derive a means of
safety from my bridge; for it is not quite certain that they would
always succeed so well as they did the first time, in their jumping
from stone to stone.
Well, then, a bridge let there be, said my wife; I see I must
consent. But let us not allow ourselves a moment of leisure till we
have completed all that is necessary for our departure. You will leave
our stock of gunpowder here, I hope; for I am not easy with a large
quantity of it so near us; a thunder-storm, or some thoughtless action
of one of the boys, might expose us to serious danger.
You are right, my love; and I will carefully attend to your
suggestion. We will keep on hand only a sufficient quantity for daily
use; I will contrive a place in the rock for the rest, where it will be
safe from the chance of fire or dampness. It is an article which,
according to the use which is made of it, may become on the one
hand, a most dangerous enemy, and, on the other, a most useful
friend.
Thus, then, we decided the important question of removing to a
new abode; after which we fixed in concert upon a plan of labour for
the day, and then awaked the boys. Their ecstasy on hearing of our
project may easily be conceived; but they expressed their fear that it
would be a long while before a bridge could be built; a single hour
appearing an age to them, with such a novelty in view as the
prospect of removing to the wood, to live under the giant trees. They,
in the fullness of their joy, entreated that the place might be called,
The promised Land.
We now began to look about for breakfast; Fritz taking care not to
neglect his monkey, who sucked one of the goats as quietly and as
contentedly as if she had been his mother. My wife undertook to milk
another, and then the cow, and afterwards gave some of the milk to
each of the children: with a part of what remained she made a sort of
soup with biscuits, and the rest she put into one of the flasks, to
accompany us in our expedition. During this time, I was preparing
the boat for another journey to the vessel, to bring away a sufficient
quantity of planks and timbers for the bridge. After breakfast we set
out; and this time I took with me Ernest as well as Fritz, that we
might accomplish our object in a shorter time. We rowed stoutly till
we reached the current, which soon drew us on beyond the bay; but
scarcely had we passed a little islet, lying to one side of us, than we
perceived a prodigious quantity of sea-gulls and other birds, whose
various and discordant sounds so disagreeably assailed us, that we
were obliged to stop our ears. Fritz would instantly have fired upon
them, if I had not prevented him. I had a great curiosity to discover
what could possibly be the reason of so numerous an assembly of
these creatures. I therefore steered to the spot; but, finding that the
boat made but little way, I hoisted my sail, that we might have the
assistance of the wind.
To Ernest our expedition afforded the highest delight. He was in
ecstasies at seeing the sail begin to swell, and the motion of the
streamer in the air. Fritz, on his part, did not for a moment take his
eyes from the islet where the birds had assembled. Presently he
suddenly exclaimed: I see what it is; the birds are all pecking, tooth
and beak, at a monstrous fish, which lies dead upon the soil.
Tooth! brother Fritz, replied Ernest; it must be curious to see birds
with teeth. Fritz, however, was right; I approached, sufficiently near
to step upon the land, and after bringing the boat to an anchor with a
heavy stone, we walked cautiously and gently up to the birds. We
soon perceived that the object which attracted them was in reality an
enormous fish, which had been thrown by the sea upon the islet, and
whose dead body lay invitingly there for all the birds which should
pass that way. Indeed, so eagerly were they occupied with the feast,
that though we were within the distance of half gun-shot, not one of
them attempted to fly off. We observed with astonishment the
extreme voracity of this plumed group; each bird was so intent upon
its prey, that nothing could have been more easy than to have killed
great numbers of them with our sticks alone: we did not, however,
envy them their prize. Fritz did not cease to express his wonder at
the monstrous size of the animal, and asked me by what means he
could have got there.
I believe, answered I, you were yourself the means; there is every
appearance that it is the very shark you so skilfully wounded
yesterday. See, here are the two balls which you discharged at its
head.
Yes, yes, it is the very same, said my young hero skipping about
for joy; I well remember I had two balls in my gun, and here they are,
lodged in his hideous head.
I grant it is hideous enough, continued I; its aspect even when
dead makes one shudder with disgust, particularly when I recollect
how easy it would have been for him to have devoured us. See what
a horrible mouth he has, and what a singular kind of mustachio
projecting above! and what a rough and prickly skin! one might
almost use it for a file. Nor is he small of his species; for I would lay
any wager that he measures more than twenty feet, from head to tail.
We ought to be thankful to Providence, and a little to our Fritz also,
for having delivered us from such a monster! But let us each take
away with us a bit of his skin, for I have an idea that it may in some
way or other be useful to us. But how to drive away these eager
intruders, so as to get at him, is the difficulty.
Ernest instantly drew out the iron ramrod from his gun, and in a
few moments killed several, by striking among them to right and left,
while all the others took their flight. Fritz and I then advanced and cut
several long strips of the skin from the head of the shark, with which
we were proceeding to our boat, when I observed, lying on the
ground, some planks and timbers which had recently been cast by
the sea on this little island. I therefore made choice of such as
seemed proper for my purpose; and, with the assistance of the crow
and a lever which we had brought with us, I found means to get them
into the boat, and thus spare ourselves the trouble of proceeding
further to the vessel. I bound the timbers together, with the planks
upon them, in the manner of a raft, and tied them to the end of the
boat; so that, in consequence of this adventure, we were ready to
return in about four hours after our departure, and might with justice
boast of having done a good day’s work. I accordingly pushed again
for the current, which soon drove us out to sea; then I tacked about,
and resumed the direct route for the bay and for our place of
embarkation, by this means avoiding the danger of touching upon
shallows. All this succeeded to my utmost wishes; I unfurled my sail,
and a brisk wind soon conveyed us to our landing-place.
While we were sailing, Fritz, at my request, had nailed the strips of
skin we cut from the shark, to the mast to dry. Ernest had been
employed in examining the birds he had killed with his ramrod. I
cannot imagine, father, said he, why you should think they are not
good to eat. What is their name?
I believe they are called sea-gulls, a bird that lives upon the
carcases of other animals, and whose flesh for that reason must
have contracted a bad flavour; there are many kinds of them, and all
of so senseless a nature, as to fly down in flocks upon dead whales,
even while the fishermen are round them cutting them up; and the
birds try to seize upon small pieces of the fat, as they hold them in
their hands; and they suffer themselves to be killed, rather than let
go their prize.
They must indeed be stupid creatures, said Fritz, to have let
Ernest kill them with the ramrod. But look here, father, you were
wrong in telling me to nail my skins to the mast; for they have curled
round in drying, and I cannot make them flat again.
That was precisely my intention, replied I, they will be much more
useful to us round than flat: besides, you have still some left, which
you may dry flat; and then we shall have a fine provision of
shagreen, if we can find out a good method to rub off the sharp
points, and afterwards to polish it.
I thought, said Ernest, that shagreen was made of ass’s skin. And
you were not mistaken, rejoined I; the best shagreen is made in
Turkey, Persia, and Tartary, from skin taken from the back of the ass
and of horses. While the skin is yet moist, it is stretched upon a kind
of hard fat; they then beat the skin, by which means the fat is
incorporated, and gives the surface the appearance of a kind of file:
but very good shagreen is also made from the skin of sea-fish,
particularly in France.
Ernest asked his brother if he knew why the mouth of the shark is
not, as in other animals, placed in the middle of the snout, but
directly under. Fritz confessed his inability to answer this question.
And for my part, continued he a little consequentially, all I know is
how to kill them when the occasion presents itself. So pray, learned
brother, be kind enough to let us share your information on the
subject, for I take for granted, your question means that you can
answer it yourself.
I suppose, rejoined Ernest, that the mouth of the shark is thus
placed, with the intention of preventing him from depopulating the
sea and the land. With so excessive a voraciousness of appetite as
he possesses, nothing would escape him, if he had the power to
seize his prey without turning his body; but as it is, there is time
enough for a smaller animal to make his escape.
Well reasoned, my young philosopher, cried I; and though we
should not always be able to comprehend the intention of the
Creator in the objects which surround us, at least the conjectures we
are induced to form respecting them, cannot fail of being a useful
exercise to the mind.
I have already said we were once more landed safely on our
shore, but no one of our family appeared. We called out to them as
loud as we could, which was answered by the same sounds in
return, and in a few minutes my wife appeared between her two little
boys returning from the river, a rising piece of ground having
concealed her from our sight: each carried a handkerchief in hand,
which appeared filled with some new prize; and little Francis had a
small fishing-net formed like a bag and strung upon a stick, which he
carried on his shoulder. No sooner did they hear our voices, than
they flew to meet us, astonished at our quick return. Jack reached us
before the rest; and his first act was to open the handkerchief he
held, and pour out a large number of lobsters at our feet: their
mother and little Francis produced each as many more, forming all
together a prodigious heap, and all alive; so that we were sure of
excellent dinners for some days at least. Some of the animals tried
to escape in different directions; and the boys in following them,
were kept in full chase, sometimes pleased and sometimes angry;
sometimes laughing, sometimes scolding at the bootless trouble they
were engaged in; for no sooner had they seized on one deserter,
than ten more had followed his example.
Now, have I not been very lucky, papa? said little Francis; for you
must know it was I who found them out! Look, there are more than
two hundred of them, and see how large they are, and what fine
claws they have! I am sure they will be quite delicious!
Father.—Excellent indeed, my little fellow, and particularly if it was
your industry that first discovered them.
Jack.—Yes, father, it was Francis who saw them first; but it was I
who ran to tell mamma, and it was I who fetched the net and put it to
rights, and it was I who went up to my knees in water to catch them.
Father.—You make a charming story of it together, my boys; but
as it is an interesting subject, you may tell me as many particulars as
you please; it is indeed an event of some importance for our kitchen,
and I have great pleasure in looking forward to partaking of a dish of
your providing.
Jack.—Well, papa, I will tell you. As soon as you were gone,
mamma sat down outside the tent and began to work, while Francis
and I took a little walk towards the river, to find out a proper place for
you to begin the bridge.
Father.—Bravo! Mr. Architect, it is you then who will direct the
workmen; but joking apart, I am much gratified to find that careless
head of yours for once employed upon a useful subject. Well then,
did you find a proper place for me to begin the bridge?
Jack.—Yes, father, yes. But listen, and you will know all. We were
advancing towards the river, and Francis was amusing himself with
taking up some parti-coloured stones, calling out whenever he found
one that seemed extraordinary: Jack, Jack, look what a beautiful
stone I have found, all yellow! I am sure it must be gold, so I shall
pound it, and make sand of it for my writing. As we reached the river,
he saw a stone of this kind just upon the brink, and kneeling down
with his head out over to take it up, he all at once cried out: Jack,
Jack, Fritz’s jackall is covered all over with lobsters! Run as fast as
you can. I sprang to him in an instant, and I saw not only the jackall
covered with them, but legions more coming in with the stream. I ran
to tell mamma, who immediately got the net which you brought from
the vessel. Partly with this net, and partly with our hands, we caught
those you see in a very few minutes; and we should have caught a
much larger number if we had not heard you call, for the river is quite
full of them. You took quite enough for once, my boy, said I: A little at
a time is the maxim that suits us best, and I should even advise your
taking the smallest of them back to the river, where they will grow
larger; we shall still have sufficient for several magnificent repasts.
This then, said I to myself, is a new source for our support: even
here, in these arid regions, we find means to procure, not only the
necessaries of life, but luxuries in abundance. May we never cease
to evince our gratitude to Providence, by the exercise of a more than
ordinary care and industry!
It was now our turn to relate the events of our voyage on the
water. Ernest gave an account of his seagulls, but it did not inspire
his mother with a desire for one of them for our next day’s dinner. We
now put our remaining lobsters into the handkerchiefs and the net,
and the boys took them to the place allotted for keeping our
provisions. My wife set about dressing some of them, and in the
mean time Fritz and I employed ourselves in untying the raft of
timbers and planks, and in taking them out of the boat. I then
imitated the example of the Laplanders, in harnessing their rein-deer
for drawing their sledges. Instead of traces, halters, &c., I put a piece
of rope with a running knot at the end, round the neck of the ass, and
passed the other end between its legs, to which I tied the piece of
wood which I wished to be removed. The cow was harnessed in the
same manner, and we were thus enabled to carry our materials,
piece by piece, to the spot which our architect Jack had chosen at
the river, as the most eligible for our bridge; and to say the truth, I
thought his judgement excellent; it was a place where the shore on
each side was steep, and of equal height; there was even on our
side, an old trunk of a tree lying on the ground, on which I rested my
principal timber.
Now then, boys, said I, the first thing is to see if our timbers are
long enough to reach to the other side: by my eye I should think they
are; but if I had a surveyor’s plane, we might be quite sure, instead
of working at a venture.
But my mother has some balls of packthread with which she
measured the height of the giant tree, interrupted Ernest, and
nothing would be more easy than to tie a stone to the end of one of
them, and throw it to the other side of the river; then we could draw it
to the very brink, and thus obtain the exact length that would be
required for our timbers.
Your idea is excellent, cried I; nothing gives me more pleasure
than to see you exercise your invention; run quickly and fetch the
packthread. He returned without loss of time; the stone was tied to
its end, and thrown across as we had planned; we drew it gently
back to the river edge, marking the place where the bridge was to
rest; we next measured the string, and found that the distance from
one side to the other was eighteen feet. It appeared to me
necessary, that to give a sufficient solidity to the timbers, I must allow
three feet at each end of extra length for fixing them, amounting
therefore in all to twenty-four feet; and I was fortunate enough to find
that many of those we had brought, did not fall short of this length.
There now remained the difficulty of conducting them across the
stream; but we determined to discuss this part of the subject while
we ate our dinner, which had been waiting for us more than an hour.
We all now proceeded homewards, and entering the kitchen, we
found our good steward had prepared a large dish of lobsters for us;
but before she would let us taste them, she insisted we should see
another useful labour she had been employed about; she
accordingly displayed two sacks intended for the ass, which she had
seamed with packthread; the work she assured us, had with difficulty
been accomplished, since for want of a needle large enough to carry
packthread, she had been obliged to make a hole with a nail for
every stitch: we might therefore judge by her perseverance in such a
task, or the ardour with which she longed to see her plan of a
removal executed. She received on this occasion, as was well her
due, abundance of compliments and thanks from her companions,
and also a little good-humoured raillery. For this time, we hurried
through our meal, all being deeply interested in the work we were
about to undertake, and concerning which, each gave his advice
without the least ceremony. The impatience we all felt to begin,
scarcely left us time to strip the lobsters of their shells, each thinking
only of the part which might be assigned him towards the execution
of the Nonpareil; for this, for mutual encouragement, was the name
we gave our bridge, even before it was in existence.
Having consulted together as to the means of laying our timbers
across the river, the first thing I did, was to attach one of them to the
trunk of the tree of which I have already spoken, by a strong cord,
long enough to turn freely round the trunk; I then fastened another
cord to the other end of the beam; this cord I fastened round a stone,
and then threw the stone across the river. I next passed the river as I
had done before, furnished with a pulley, which I secured to a tree; I
passed my second cord through the pulley, and recrossing the river
with this cord in my hand, I contrived to harness the ass and the cow
to the end of the cord. I next drove the animals from the bank of the
river; they resisted at first, but I made them go by force of drawing. I
first fixed one end of the beam firm to the trunk of the tree, and then
they drew along the other end, so as gradually to advance over the
river: presently, to my great joy, I saw it touch the other side, and at
length become fixt and firm by its own weight. In a moment Fritz and
Jack leaped upon the timber, and, in spite of my paternal fears,
crossed the stream with a joyful step upon this narrow but effective
bridge.
The first timber being thus laid, the difficulty of our undertaking
was considerably diminished; a second and a third were fixt in
succession, and with the greatest ease. Fritz and I, standing on
opposite sides of the river, placed them at such distances from each
other, as was necessary to form a broad and handsome bridge: what
now remained to be done, was to lay some short planks across them
quite close to each other, which we executed so expeditiously, that
our whole undertaking was completed in a much shorter time than I
should have imagined possible. The reader should have seen our
young workmen, to form the least conception of the delight they felt:
they jumped, and danced, and played a thousand antics, and uttered
a thousand joyful sounds upon their bridge. For my own part, I could
hardly restrain myself from joining in these demonstrations of their
perfect happiness; and my wife, who had been the mover of all our
operations, was as little disposed to a silent calm enjoyment of our
success, as any of the rest: she ran to one, and then to another,
embracing each in turn, and was never tired of passing and
repassing on our piece of workmanship, which was every where safe
and even, and at least ten feet in breadth. I had not fastened the
cross planks to each other, for they appeared to be close and firm
without it; and besides, I recollected that in case of danger from any
kind of invasion, we could with the greater ease remove them, and
thus render the passage of the river more difficult. Our labour
however had occasioned us so much fatigue, that we found
ourselves unable for that day to enter upon new exertions; and the
evening beginning to set in, we returned to our home, where we
partook heartily of an excellent supper, and went to bed.
CHAPTER IX.
Change of abode.

As soon as we were all up and had breakfasted, the next morning,


I assembled all the members of my family together, to take with them
a solemn farewell of this our first place of reception from the horrible
disaster of the shipwreck. I confess that for my own part I could not
leave it without much regret; it was a place of greater safety than we
were likely again to meet with; it was also nearer to the vessel: but it
was sufficient for me to know that the kind and faithful companion of
my misfortunes had conceived an unalterable distaste for it, to
incline me to yield my own opinion and my wishes. I should indeed
consider myself unworthy of such a partner, if I could have felt
hesitation in a point of so much interest to her feelings. I thought it
right to represent strongly to my sons, particularly to the youngest,
the danger of exposing themselves as they had done the evening
before, along the river. We are now going, continued I, to inhabit an
unknown country, which is not so well protected by nature as that we
are leaving; we are unacquainted both with the soil and its
inhabitants, whether human creatures or beasts; it is therefore
necessary to use the utmost caution, to make it a rule never to
remain separate from each other; particularly you young ones must
take care not to run on before, or stay too far behind. This you must
promise, my boys. Having unburdened my mind of this necessary
charge, we prepared for setting out. I directed my sons to assemble
our whole flock of animals, and to leave the ass and the cow to me,
that I might load them with the sacks as before concerted; I had filled
these at the two ends, and made a slit longways in the middle of
each of them, and to each side of the slits I tied several long pieces
of cord, which crossing each other and being again brought round
and fastened, served to hold the sacks firmly on the back of the
animal. We next began to put together all the things we should stand
most in need of, for the two or three first days, in our new abode;
working implements, kitchen utensils, the captain’s service of plate,
and a small provision of butter, &c. &c. I put these articles into the
two ends of each sack, taking care that the sides should be equally
heavy, and then fastened them on. I next added our hammocks and
other coverings to complete the load, and we were about to begin
our march when my wife stopped me. I cannot prevail upon myself,
said she, to leave our fowls behind us to pass the night by
themselves; for I fear they would infallibly become the prey of the
jackalls. We must, somehow or other, contrive a place for them
among the luggage, and also one for our little Francis, who cannot
walk so far, and on that account would not fail to interrupt our speed.
There is also my enchanted bag, which I recommend to your
particular care, said she, smiling, for who can tell what may yet pop
out of it for your good pleasure!
Women, for their part, never fail to have more things to carry than
there are places to put them in, said I, also laughing: however, let us
see how handsomely I shall be able to provide for what belongs to
you, my love. Fortunately, I had already thought of making the ass’s
load as light as possible, foreseeing that it would be necessary he
should carry our little one a part of the way. I now accordingly placed
the child upon his back, fixing the enchanted bag in such a way as to
support him, and I tied them together upon the ass with so many
cords, that the animal might even have galloped without any danger
of his falling off.
In the mean while, the other boys had been running after the
cocks and hens and the pigeons, but had not succeeded in catching
one of them; so they returned empty-handed and in ill-humour. Little
blockheads! said their mother, see how you have heated yourselves
in running after these untractable creatures! I could have put you in a
way to catch them in a moment; come along with me, and see.—
Yes, yes, you may think so, mother, said Jack, a little sulky, but I will
give you leave to roast me in the place of the first fowl that you shall
be able to catch. Poor Jack, said she laughing, you will then soon be
on the spit, I can tell you; which would really be a pity, considering
what better things we might do with you; though, to say the truth, you
have not shown that you have more brains than a goose, in thinking
to catch the animals by running after them in this manner. She now
stepped into the tent, and brought out two handfuls of peas and oats,
and by pronouncing a few words of invitation in the accustomed
tone, the birds all flocked round her in a moment. She then walked
slowly before them, dropping the grain all the way, till they had
followed her into the tent. When she perceived that they were all in
the inside, and busily employed in picking up the grain, she shut the
entrance, and caught one after the other without the smallest
difficulty. The boys looked at each other half-ashamed, though much
amused with the adventure. Grant me a reprieve from the spit,
mother, cried Jack, and I will do all I can to help you in securing your
prisoners. Accordingly, he set himself to work, and had soon caught
the whole. They were then tied by the feet and wings, put into a
basket covered with a net, and placed in triumph on the top of our
luggage. Ernest suggested the placing two bent sticks arch-ways
across the basket, and throwing a blanket over it, that the want of
light might incline them to repose; for, with the clatter they made, it
was impossible to hear each other speak.
We packed up every thing we were obliged to leave, and placed it
in the tent, which we carefully closed, and, for greater security,
fastened down the ends of the sail-cloth at the entrance, by driving
stakes through them into the ground. We ranged a number of
vessels, both full and empty, round the tent, to serve as a rampart,
and thus we confided to the protection of heaven our remaining
treasures. At length we set ourselves in motion: each of us, great
and small, carried a gun upon his shoulder, and a game bag at his
back. Children are always fond of a change of place; ours were full
of joy and good-humour; nor was their mother less affected with the
same cause; she walked before with her eldest son, the cow and the
ass immediately behind them; the goat conducted by Jack came
next; the little monkey was seated on the back of his nurse, and
made a thousand grimaces. After the goats, came Ernest,
conducting the sheep, while I, in my capacity of general
superintendant, followed behind and brought up the rear; the dogs
for the most part paraded backwards and forwards, thus seeming to
play the part of adjutants. Our march was slow, and there was
something solemn and patriarchal in the spectacle we exhibited; I
fancied we must resemble our forefathers journeying in the deserts,
accompanied by their families and their possessions. Now then,
Fritz, cried I, you have the specimen you wished for of the patriarchal
mode of life; what do you think of it? I like it much, father, replied he:
I never read the Bible without wishing I had lived in those good
times.
And I too, said Ernest, I am quite delighted with it, I cannot help
fancying myself not merely a patriarch but a Tartar, or an Arab, and
that we are about to discover I know not how many new and
extraordinary things. Is it not true, father, that the Tartars and the
Arabs pass their lives in journeying from one place to another, and
carrying all they have about them?
It is certainly for the most part true, Ernest, replied I, and they are
denominated wandering tribes; but they generally perform their
journeys attended by horses and camels, by means of which they
can proceed a little faster, than if, like us, they had only an ass and a
cow. For my part, I should not be sorry if I were quite sure that the
pilgrimage we are now making, would be our last.
And I too am of your way of thinking, cried my wife, and I hope that
in our new abode we shall be so well satisfied with the shade of such
luxuriant trees, that we shall not be inclined to rove. Let us, however,
think as little as possible of the fatigue which seems to be our lot
today, since tomorrow you will all be ready to thank me for having
been the occasion of it.
Be assured, my dear, said I, that we have adopted your plans, and
endure the fatigue they occasion, with cheerfulness, and that one
and all, are already grateful to you for their future happiness; which
happiness will be still increased by the reflection, that to your kind
and anxious exertions it has been that we are indebted for it.
We had now reached our bridge, and advanced half way across it,
when the sow for the first time took the fancy of joining us, and, by
the uncouth and listless figure she made, contributed to the pictorial
effect of our procession. At the moment of our departure, she had
shown herself so restive and indocile, that we had been compelled to
leave her behind us; but when she saw that we had all left the place,
she set out voluntarily to overtake us: but she took care to apprize
us, by her continual grunting, that she disapproved of our migration.
On the other side of the river, we experienced an inconvenience
wholly unexpected. The nutritious aspect of the grass, which grew
here in profusion, was too strong a temptation for our animals, who,
unable to resist, strayed from us in every direction to feed
voluptuously upon it; so that, without the assistance of our dogs, we
should not have been able to bring them back to the line of our
procession. These active creatures were of great use to us on this
occasion, and when every thing was restored to proper order, we
were able to continue our journey. For fear however of a similar
occurrence, I directed our march to the left, along the sea side,
where there was not a sufficient quantity of grass to attract them.
But scarcely had we advanced a few steps on the sands, when
our two dogs, which had stayed behind among the grass, set up a
loud barking, mixt at intervals with howling, as if they had been
wounded, or were engaged in an encounter with some formidable
animal. Fritz in an instant lifted his gun to his cheek, and was ready
to fire; Ernest, always somewhat timid, drew back to his mother’s
side; Jack ran bravely after Fritz with his gun upon his shoulder;
while I, fearing the dogs might be attacked by some dangerous wild
beast, prepared myself to run to their assistance. But youth is always
full of ardour; and in spite of all my exhortations that they would
advance with caution, my boys, eager for the event, made but three
jumps to the place from which the noise proceeded. In an instant
Jack had turned to meet me, clapping his hands and calling out,
Come quickly, father, come quickly, here is a monstrous porcupine!
I soon reached the spot, and perceived that it was really as they
said, bating a little exaggeration. The dogs were running to and fro
with bloody noses, about the animal; and when they approached too
near him, he made a frightful noise, and darted his quills so suddenly
at them, that a great number had penetrated the skins of our valiant
dogs, and remained sticking in them; and it was no doubt the pain
they occasioned, which made them howl so violently.
While we were looking on, Jack determined on an attack, which
succeeded marvellously well. He took one of the pistols which he
carried in his belt, and aimed it so exactly at the head of the
porcupine, that he fell dead the instant he fired, and before we had a
notion of what he was about. This success raised Jack to the height
of joy and vanity; while Fritz, on the other hand, felt a sensation of
jealousy almost to shedding tears. Is it right, Jack, said he, that such
a little boy as you, should venture to fire off a pistol in this manner?
How easily might you have wounded my father or me, or one of the
dogs, by so rash an action! Oh yes, to be sure, and what do you
suppose hindered me from seeing that you were all behind me? Do
you think I fired without taking care of that? Do you take me for an
idiot? The porcupine could tell you about that, brother Fritz, if he
could but speak. My first fire—pop—dead as a herring! This is
something like, brother Fritz, and you would be glad enough to have
had such a chance yourself!
Fritz only replied by a motion of his head. He was out of humour,
because his younger brother had deprived him of the honour of the
day; and he sought a subject of complaint against him, as the wolf
did with the poor little lamb. Come, come, boys, said I, let me hear
no envious speeches and no reproaches; luck for one to-day, for
another to-morrow; but all for the common good. Jack was, perhaps,
a little imprudent, but you must allow that he showed both skill and
courage; let us not therefore tarnish the glory of his action. We now
all got round the extraordinary animal, on whom nature has
bestowed a strong defence, by arming his body, all over, with long
spears. The boys were absolutely at a loss what means to use for
carrying away his carcase. They thought of dragging it along the
ground; but as often as they attempted to take hold, there was
nothing but squalling, and running to show the marks made by his
quills on their hands. We must leave him behind, said they; but it is a
great pity.
Not for an empire, cried Jack, shall he be left there, for my mother
must have a sight of him. In saying this, he tied one corner of his
handkerchief round the neck of the animal, and drew him by the
other to the place where we had left his mother in care of our

You might also like