100% found this document useful (10 votes)
338 views81 pages

Microsoft Visual C# 2017 An Introduction To Object Oriented Programming 7th Edition by Joyce Farrell ISBN 1337102100 9781337102100

The document provides information about the book 'Microsoft Visual C# 2017: An Introduction to Object-Oriented Programming' by Joyce Farrell, including its ISBN and a link to download the full version. It also lists several other recommended textbooks on object-oriented programming with links for downloading. The document emphasizes the availability of various educational resources at ebookball.com.

Uploaded by

woumbathilia
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (10 votes)
338 views81 pages

Microsoft Visual C# 2017 An Introduction To Object Oriented Programming 7th Edition by Joyce Farrell ISBN 1337102100 9781337102100

The document provides information about the book 'Microsoft Visual C# 2017: An Introduction to Object-Oriented Programming' by Joyce Farrell, including its ISBN and a link to download the full version. It also lists several other recommended textbooks on object-oriented programming with links for downloading. The document emphasizes the availability of various educational resources at ebookball.com.

Uploaded by

woumbathilia
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 81

Visit ebookball.

com to download the full version and


explore more ebook or textbook

Microsoft Visual C# 2017 An Introduction to Object


Oriented Programming 7th Edition by Joyce Farrell
ISBN 1337102100 9781337102100

_____ Click the link below to download _____


https://ebookball.com/product/microsoft-visual-c-2017-an-
introduction-to-object-oriented-programming-7th-edition-by-
joyce-farrell-isbn-1337102100-9781337102100-25038/

Explore and download more ebook or textbook at ebookball.com


Here are some recommended products that we believe you will be
interested in. You can click the link to download.

Beginning C 3 0 an introduction to object oriented


programming 1st edition by Jack Purdum 0470261293
978-0470261293
https://ebookball.com/product/beginning-c-3-0-an-introduction-to-
object-oriented-programming-1st-edition-by-jack-
purdum-0470261293-978-0470261293-15238/

Object Oriented Programming Using C An Introduction 1st


Edition by Pardoe, King 0333692411 978-0333692417

https://ebookball.com/product/object-oriented-programming-using-c-an-
introduction-1st-edition-by-pardoe-
king-0333692411-978-0333692417-15282/

An Introduction to Object Oriented Programming With Java


5th Edition by Thomas Wu 0073523305 9780073523309

https://ebookball.com/product/an-introduction-to-object-oriented-
programming-with-java-5th-edition-by-thomas-
wu-0073523305-9780073523309-17244/

An Introduction to Object Oriented Programming With Java


5th Edition by Thomas Wu 0073523305 9780073523309

https://ebookball.com/product/an-introduction-to-object-oriented-
programming-with-java-5th-edition-by-thomas-
wu-0073523305-9780073523309-15256/
An Introduction to Object Oriented Programming With Java
5th Edition by Thomas Wu 0073523305 9780073523309

https://ebookball.com/product/an-introduction-to-object-oriented-
programming-with-java-5th-edition-by-thomas-
wu-0073523305-9780073523309-15330/

An Introduction to Object Oriented Programming with Java


5th Edition by Thomas Wu ISBN 9780073523309 0073523305

https://ebookball.com/product/an-introduction-to-object-oriented-
programming-with-java-5th-edition-by-thomas-wu-
isbn-9780073523309-0073523305-15552/

An Introduction to Object Oriented Programming with Java


5th Edition by Thomas Wu ISBN 0073523305 9780073523309

https://ebookball.com/product/an-introduction-to-object-oriented-
programming-with-java-5th-edition-by-thomas-wu-
isbn-0073523305-9780073523309-16398/

C Programming An Object Oriented Approach 1st Edition by


Behrouz Forouzan, Richard Gilberg 0073523380 9780073523385

https://ebookball.com/product/c-programming-an-object-oriented-
approach-1st-edition-by-behrouz-forouzan-richard-
gilberg-0073523380-9780073523385-15328/

Object Oriented Programming using C 1st Edition by Simon


Kendal 9788776818142

https://ebookball.com/product/object-oriented-programming-using-c-1st-
edition-by-simon-kendal-9788776818142-15260/
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-202
Microsoft® Visual C#® 2017
An Introduction to Object-Oriented Programming, SEVENTH Edition

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

Microsoft® Visual C#® 2017


An Introduction to Object-Oriented Programming

J o y c e Fa r r e l l

Australia • Brazil • Mexico • Singapore • United Kingdom • United States

Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-202
Microsoft® Visual C#® 2017: An © 2018, 2016 Cengage Learning
Introduction to Object-Oriented Unless otherwise noted, all content is © Cengage.
Programming, Seventh Edition
Joyce Farrell ALL RIGHTS RESERVED. No part of this work covered by the copyright
herein may be reproduced or distributed in any form or by any means,
SVP, GM Science, Technology & Math: except as permitted by U.S. copyright law, without the prior written
Balraj S. Kalsi permission of the copyright owner.

Senior Product Director: Unless otherwise noted all screenshots are courtesy of Microsoft
Kathleen McMahon Corporation
Unless otherwise noted all tables/­figures exhibits are © 2018 Cengage ®
Product Team Manager:
Kristin McNary For product information and technology assistance, contact us at
Cengage Learning Customer & Sales Support, 1-800-354-9706
Associate Product Manager:
Kate Mason For permission to use material from this text or product, submit all
requests online at www.cengage.com/permissions.
Senior Director, Development: Further permissions questions can be e-mailed to
Julia Caballero [email protected]

Senior Content Development


Manager: Leigh Hefferon Library of Congress Control Number: 2017941097

Senior Content Developer: Alyssa Pratt Softbound ISBN: 978-1-337-10210-0


Loose Leaf ISBN: 978-1-337-68577-1
Product Assistant: Jake Toth
Cengage Learning
Marketing Director: Michele McTighe 20 Channel Center Street
Boston, MA 02210
Marketing Manager: USA
Jeffrey A. Tousignant
Cengage Learning is a leading provider of customized learning solutions
Senior Content Project Manager: with employees residing in nearly 40 different countries and sales in more
Jennifer F
­ eltri-George than 125 countries around the world. Find your local representative at
www.cengage.com
Senior Designer/Art Director:
Diana Graham Cengage Learning products are represented in Canada by
Nelson Education, Ltd.
Production Service/Composition:
SPi Global To learn more about Cengage Learning, visit www.cengage.com
Purchase any of our products at your local college store or at our
Cover image: Colormos/Photodisc/
preferred online store www.cengagebrain.com
Getty Images
Notice to the Reader
Publisher does not warrant or guarantee any of the products described
herein or perform any independent analysis in connection with any of
the product i­nformation contained herein. Publisher does not assume,
and expressly d ­ isclaims, any obligation to obtain and include
­information other than that provided to it by the manufacturer. The
reader is expressly warned to consider and adopt all safety precautions
that might be indicated by the activities described herein and to avoid
all potential hazards. By following the i­nstructions contained herein, the
reader willingly assumes all risks in c­ onnection with such instructions.
The publisher makes no representations or warranties of any kind,
including but not limited to, the warranties of fitness for particular
­purpose or merchantability, nor are any such representations implied
with respect to the material set forth herein, and the p ­ ublisher takes no
responsibility with respect to such material. The publisher shall not be
­liable for any special, consequential, or exemplary damages resulting, in
whole or part, from the readers’ use of, or reliance upon, this material.

Printed in the United States of America


Print Number: 01 Print Year: 2017

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

Pref ace . . . . . . . . . . . . . . . . . . xv
CHAPTER 1 A F ir s t Pro g r a m Usi ng C # . . . . . . . . . . 1
CHAPTER 2 U s in g Dat a . . . . . . . . . . . . . . . . 47
CHAPTER 3 Using GUI Objects and the Visual Studio IDE . . . . 99
CHAPTER 4 M ak in g Decis i o ns . . . . . . . . . . . . 133
CHAPTER 5 Lo o pin g . . . . . . . . . . . . . . . . . 185
CHAPTER 6 U s in g A r r ays . . . . . . . . . . . . . . 223
CHAPTER 7 U s in g M et h o ds . . . . . . . . . . . . . . 265
CHAPTER 8 A dvan ced M e t ho d Concepts . . . . . . . . 307
CHAPTER 9 U s in g C las s es and Obj ects . . . . . . . . 351
CHAPTER 10 In t ro du ct io n to I nheri tance . . . . . . . . 421
CHAPTER 11 E xcept io n Handl i ng . . . . . . . . . . . . 483
CHAPTER 12 U s in g C o n t rol s . . . . . . . . . . . . . . 535
CHAPTER 13 H an dlin g Eve nt s . . . . . . . . . . . . . 597
CHAPTER 14 F iles an d St ream s . . . . . . . . . . . . 645
Appen dix A Oper at o r Pre cedence and Associ ati v i ty . . . 695
Appen dix B U n der s t an ding Numberi ng Sy stems
an d Co m pu t er Co des . . . . . . . . . . . 697
Appen dix C U s in g t h e IDE Edi t or . . . . . . . . . . . 707
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-202
Contents
vi

Pref ace . . . . . . . . . . . . . . . . . . xv

CHAP TER 1 A F ir s t Pro g ram Usi ng C # . . . . . . . . . . 1


The Programming Process . . . . . . . . . . . . . . . . . . 2
Procedural and Object-Oriented Programming . . . . . . . . . 4
Features of Object-Oriented Programming Languages . . . . . 7
The C# Programming Language . . . . . . . . . . . . . . . 9
Writing a C# Program that Produces Output . . . . . . . . . 11
Selecting Identifiers . . . . . . . . . . . . . . . . . . . . 14
Improving Programs by Adding Comments
and Using the System Namespace . . . . . . . . . . . . . 18
Adding Program Comments . . . . . . . . . . . . . . . . 18
Using the System Namespace . . . . . . . . . . . . . . 19
Compiling and Executing a C# Program . . . . . . . . . . . 23
Compiling Code from the Command Prompt . . . . . . . . . 24
Compiling Code Using the Visual Studio IDE . . . . . . . . . 26
Noticing the Differences Between the Programs
in the Text Editor and the IDE . . . . . . . . . . . . . . 29
Deciding Which Environment to Use . . . . . . . . . . . . 30
Chapter Summary . . . . . . . . . . . . . . . . . . . . . 38
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . . 38
Review Questions . . . . . . . . . . . . . . . . . . . . . 42
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . 44

CHAP TER 2 U s in g Dat a . . . . . . . . . . . . . . . . 47


Declaring Variables . . . . . . . . . . . . . . . . . . . . . 48
Displaying Variable Values . . . . . . . . . . . . . . . . . . 52
Variable Alignment . . . . . . . . . . . . . . . . . . . . 55
Using the Integral Data Types . . . . . . . . . . . . . . . . 56
Using Floating-Point Data Types . . . . . . . . . . . . . . . 59
Formatting Floating-Point Values . . . . . . . . . . . . . . 60
Using Arithmetic Operators . . . . . . . . . . . . . . . . . 63
Using Shortcut Arithmetic Operators . . . . . . . . . . . . 64

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


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-202
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-202


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-202
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-202


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-202
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-202


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-202
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-202
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-202
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-202
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-202
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-202
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-202
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-202
Features

Features
Microsoft Visual C# 2017 is a superior textbook because it also includes the following new
features:
•• C# 7.0 in Visual Studio 2017—This edition is written and tested using the latest edition xxi
of C#.
•• Conventional method names—All methods have been rewritten to follow the C# naming
convention of starting with an uppercase letter.
•• Splitting strings—The new version of C# automatically splits long strings into multiple
concatenated strings.
•• Returning values by reference—A new feature in C# allows methods to return a reference.
•• Exercises—Each chapter concludes with meaningful programming exercises that provide
additional practice of the skills and concepts you learned in the chapter. Several new
exercises appear in each chapter of this edition, and all the replaced exercises and solutions
are available to instructors to provide as additional student assignments or to use as the basis
for lectures.
Microsoft Visual C# 2017 also includes the following features:
•• Early GUI applications—Students can begin to create GUI applications in Chapter 3. The
earlier introduction helps engage students who have used GUI applications their entire
lives. In subsequent chapters on selections, loops, arrays, and methods, students apply
concepts to applications in both console and GUI environments. This approach keeps some
examples simple while increasing the understanding that input, processing, and output are
programming universals, no matter what interface is used. The book is structured so that
students who want to skip Chapter 3 until they understand object-oriented programming
can do so with no loss of continuity.
•• Objectives—Each chapter begins with a list of objectives so you know the topics that will be
presented in the chapter.
•• Notes—These tips provide additional information—for example, an alternative method
of performing a procedure, another term for a concept, background information on a
technique, or a common error to avoid.
•• Figures—Each chapter contains many figures. Code figures are most frequently 25 lines or
shorter, illustrating one concept at a time. Frequently placed screen shots show exactly how
program output appears. In this edition, all C# keywords that appear in figures are bold to
help them stand out from programmer-created identifiers.
•• Summaries—Following each chapter is a summary that recaps the programming concepts
and techniques covered in the chapter. This feature helps you to check your understanding
of the main points in each chapter.

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

•• Key Terms—Each chapter includes a list of newly introduced vocabulary, shown


in the order of appearance in the text. The list of key terms provides a review of
the major concepts in the chapter.
•• Two Truths & a Lie—This short quiz appears after each main chapter section,
xxii with answers provided. This quiz contains three statements—two true and
one false—and the student must identify the false one. These quizzes provide
students with immediate feedback as they read, without “giving away” answers
to the existing multiple-choice and programming problem questions.
•• Review Questions—Each chapter contains 20 multiple-choice review questions
that provide a review of the key concepts in the chapter.
•• Debugging Exercises—Each chapter contains four programs that have syntax
and/or logical errors for you to fix. Completing these exercises provides valuable
experience in locating errors, interpreting code written by others, and observing
how another programmer has approached a problem.
•• Cases—Each chapter contains two running case problems. These cases
represent projects that continue to grow throughout a semester using concepts
learned in each new chapter. Two cases allow instructors to assign different
cases in alternate semesters, or to divide students in a class into two case teams.
•• Program Code—The downloadable student files provide code for each full
program presented in the chapter figures. Providing the code allows students
to run it, view the results for themselves, and experiment with multiple input
values and changes to the code.
•• Glossary—A glossary contains definitions for all key terms in the book,
presented in alphabetical order.
•• Video lessons—Each chapter includes three or more video lessons produced
by the author. These short videos provide instruction, further explanation, or
background about a topic covered in the corresponding chapter. These videos
are especially useful for online classes, for student review before exams, and for
students who are audio learners.
•• Quality—Every program example in the book, as well as every exercise, case
project, and game solution, was tested by the author and again by a Quality
Assurance team using Visual Studio 2017.

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

Instructor Resources
MindTap
MindTap activities for Farrell's Microsoft Visual C# 2017: An Introductino to Object-Oriented xxiii
Programming, Seventh Edition, are designed to help students master the skills they need in
today's workforce. Research shows employers need critical thinkers, troubleshooters, and
creative problem-solvers to stay relevant in our fast-paced, technology-driven world. MinTap
< MindTap >helps you achieve this with assignments and activities that provide hands-on
practice and real-life relevance. Students are guided through assignments that help them
master basic knowledge and understanding before moving on to more challenging problems.
All MindTap activities and assignments are tied to defined unit learning objectives. Hands-on
coding labs provide real-life application and practice. Readings and dynamic visualizations
support the lecture, while a post-course assessment measures exactly how much a student has
learned. MindTap provides the analytics and reporting to easily see where the class stands in
terms of progress, engagement, and completion rates. Use the content and learning path as-is
or pick-and-choose how our materials will wrap around yours. You control what the students
see and when they see it. Learn more at http://www.cengage.com/mindtap/.

Instructor Companion Site


The following teaching tools are available for download at the Companion Site for this text.
Simply search for this text at www.cengagebrain.com and choose "Instructor Downloads." An
instructor login is required.
•• Instructor’s Manual: The Instructor’s Manual that accompanies this textbook includes
additional instructional material to assist in class preparation, including items such as
Overviews, Chapter Objectives, Teaching Tips, Quick Quizzes, Class Discussion Topics,
Additional Projects, Additional Resources, and Key Terms. A sample syllabus is also
available.
•• Test Bank: Cengage Testing Powered by Cognero is a flexible, online system that allows
you to:
w author, edit, and manage test bank content from multiple Cengage Learning solutions
w create multiple test versions in an instant
w deliver tests from your LMS, your classroom, or wherever you want
•• PowerPoint Presentations: This text provides PowerPoint slides to accompany each
chapter. Slides can be used to guide classroom presentations, to make available to students
for chapter review, or to print as classroom handouts. Files are provided for every figure in
the text. Instructors can use the files to customize PowerPoint slides, illustrate quizzes, or
create handouts.
•• Solutions: Solutions to “You Do It” exercises and all end-of-chapter exercises are available.
Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-202
C o ntents Contents Acknowledgments

Acknowledgments
Thank you to all of the people who make this book a success, including Alyssa Pratt,
Senior Content Developer; and Jennifer Feltri-George, Content Project Manager. I want to
acknowledge every Cengage Learning Consultant who travels the country guiding instructors
xxiv in their choices of educational materials.
Thanks, too, to my husband, Geoff, for his constant support and encouragement. Finally, this
book is dedicated to the newest member of our family arriving in June, 2017, after this book
goes to print. We don't yet know your first name, Baby Farrell-Peterson, but I am excited and
filled with love awaiting your arrival.
Joyce Farrell

Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-202
Read This Before
You Begin xxv

To the User of the Data Files


To complete the steps and projects in this book, you need data files that have been created
specifically for this book. Your instructor will provide the data files to you. You also can obtain
the files electronically from CengageBrain.com. Find the ISBN of your title on the back cover
of your book, then enter the ISBN in the search box at the top of the CengageBrain home page.
You can find the data files on the product page that opens. Note that you can use a computer in
your school lab or your own computer to complete the exercises in this book.

Using Your Own Computer


To use your own computer to complete the steps and exercises, you will need the following:
•• Software—Microsoft Visual C# 2017, including the Microsoft .NET Framework.
•• Hardware—Minimum requirements identified by Microsoft are a 1.8 GHz CPU, 2 GB of
RAM, 1GB to 40GB of hard disk space, depending on features installed, and a display with a
resolution of 1280 by 720.
•• Operating system—Windows 10, or, with updates, 7 or 8.

Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-202
Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-202
CHAPTER 1
A First Program
Using C#

Upon completion of this chapter, you will be able to:

••Describe the programming process


••Differentiate between procedural and object-oriented
programming
••Describe the features of object-oriented programming
languages
••Describe the C# programming language
••Write a C# program that produces output
••Select identifiers to use within your programs
••Improve programs by adding comments and using the
System namespace
••Compile and execute a C# program using the command
prompt and using Visual Studio

Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-202
CHAPTER 1 A First Program Using C#

Programming a computer is an interesting, challenging, fun, and sometimes frustrating task.


As you learn a programming language, you must be precise and careful as well as creative.
Computer programmers must learn to plan a program’s logic, and can choose from a variety
of programming languages, such as Visual Basic, Java, and C++, in which to implement their
logic. C# (pronounced “C Sharp”) is a relatively-new programming language that offers a wide
2
range of options and features. As you work through this book, you will master many of them,
one step at a time. If this is your first programming experience, you will learn new ways to
approach and solve problems and to think logically. If you know how to program but are new
to C#, you will be impressed by its capabilities.
In this chapter, you will learn about the background of programming that led to the
development of C#, and you will write and execute your first C# programs.

The Programming Process


A computer program is a set of instructions that tells a computer what to do. Programs are also
called software; software comes in two broad categories:
•• System software describes the programs that operate the computer. Examples include
operating systems such as Microsoft Windows, Mac OSX, and Linux.
•• Application software describes the programs that allow users to complete tasks such as
creating documents, calculating paychecks, and playing games. (Application software
programs are often called apps.)
The physical devices that make up a computer system are called hardware. Internally,
computer hardware is constructed from circuitry that consists of small on/off switches; the
most basic circuitry-level language that computers use to control the operation of those
switches is called machine language. Machine language is expressed as a series of 1s and
0s—1s represent switches that are on, and 0s represent switches that are off. If programmers
had to write computer programs using machine language, they would have to keep track
of the hundreds of thousands of 1s and 0s involved in programming any worthwhile task.
Not only would writing a program be a time-consuming and difficult task, but modifying
programs, understanding others’ programs, and locating errors within programs all would
be cumbersome. Additionally, the number and location of switches vary from computer to
computer, which means you would need to customize a machine-language program for every
type of machine on which the program had to run.
Fortunately, programming has become easier because of the development of high-level
programming languages. A high-level programming language allows you to use a limited
vocabulary of reasonable keywords. Keywords are predefined and reserved identifiers that have
special meaning in a language. High-level language programs contain keywords such as read,
write, and add that you use instead of the sequence of on/off switches that perform these tasks.
High-level languages also allow you to assign reasonable names to areas of computer memory;
you can use names without spaces, such as hoursWorked or payRate, rather than having to
remember the memory locations (switch numbers) of those values.

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

Camel casing, or lower camel casing, describes the style of identifiers such as hoursWorked and
payRate that appear to have a hump in the middle because they start with a lowercase letter but contain
uppercase letters to identify new words. By convention in C#, data item names use camel casing.
The C# programming language is case sensitive. Therefore, if you create an identifier named payRate,
you cannot refer to it later using identifiers such as PayRate or payrate.
3

Each high-level language has its own syntax, or rules of the language. For example, to produce
output, you might use the verb print in one language and write in another. All languages have
a specific, limited vocabulary, along with a set of rules for using that vocabulary. Programmers
use a computer program called a compiler to translate their high-level language statements
into machine code. The compiler issues an error message each time a programmer commits a
syntax error—that is, each time the programmer uses the language incorrectly. Subsequently,
the programmer can correct the error and attempt another translation by compiling the
program again. The program can be completely translated to machine language only when all
syntax errors have been corrected. When you learn a computer programming language such
as C#, C++, Visual Basic, or Java, you must learn both the vocabulary and syntax rules for that
language.

In some languages, such as BASIC, the language translator is called an interpreter. In others, such as
assembly language, it is called an assembler. The various language translators operate differently, but the
ultimate goal of each is to translate the higher-level language into machine language.

In addition to learning the correct syntax for a particular language, a programmer must
understand computer programming logic. The logic behind any program involves executing
the various statements and procedures in the correct order to produce the desired results.
For example, you might be able to execute perfect individual notes on a musical instrument,
but if you do not execute them in the proper order (or execute a B-flat when an F-sharp was
expected), no one will enjoy your performance. Similarly, you might be able to use a computer
language’s syntax correctly but be unable to obtain correct results because the program is not
constructed logically. Examples of logical errors include multiplying two values when you
should divide them, or attempting to calculate a paycheck before obtaining the appropriate
payroll data. The logic used to solve a problem might be identical in two programs, but the
programs can be written in different languages, each using different syntax.

Since the early days of computer programming, program errors have been called bugs. The term is often
said to have originated from an actual moth that was discovered trapped in the circuitry of a computer
at Harvard University in 1945. Actually, the term bug was in use prior to 1945 to mean trouble with any
electrical apparatus; even during Thomas Edison’s life, it meant an “industrial defect.” In any case, the
process of finding and correcting program errors has come to be known as debugging the program.

Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-202
CHAPTER 1 A First Program Using C#

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.

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


such as read, write, or add instead of the sequence of on/off switches that perform
these tasks.
2. Each high-level programming language has its own syntax.
3. Programmers use a computer program called a compiler to translate machine code
into a high-level language they can understand.

level language statements into machine code.


The false statement is #3. Programmers use a compiler to translate their high-

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
language to create and name computer memory locations that can hold values, and you write a
series of steps or operations to manipulate those values. For example, a simple payroll program
might contain instructions similar to the following:
get hoursWorked
pay = hoursWorked * 10.00
output pay
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,
the memory location referenced by the name hoursWorked might contain different values
at different times for different employees. During 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 it by a pay rate, and printing it on paper.

Examples of procedural programming languages include C and Logo.

Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-202
Procedural and Object-Oriented Programming 

For convenience, the individual operations used in a procedural program often are grouped
into logical units called methods. For example, a series of four or five comparisons and
calculations that together determine an employee’s withholding tax value might be grouped as
a method named CalculateWithholdingTax().
5
Capitalizing the first letter of all new words in an identifier, even the first one, as in
CalculateWithholdingTax(), is a style called Pascal casing or upper camel casing.
Although it is legal to start a method name with a lowercase letter, the convention used in C# is
for methods to be named using Pascal casing. This helps distinguish them from variables, which
conventionally use lower camel casing. Additionally, in C# all method names are followed by a set of
parentheses. When this book refers to a method, the name will be followed with parentheses.

A procedural program divides a problem solution into multiple methods, each with a unique
name. The program then calls or invokes the methods to input, manipulate, and output the
values stored in those locations. A single procedural program often contains hundreds of
variables and thousands of method calls.

Depending on the programming language, methods are sometimes called procedures, subroutines,
or functions. In C#, the preferred term is methods.

Object-oriented programming (OOP) is an extension of


Paycheck procedural programming. OOP uses variables and methods like
payee
procedural programs do, but it focuses on objects that contain
hoursWorked the variables and methods. An object is a concrete entity that
grossPay has attributes and behaviors. The attributes of an object are
the features it “has”; the values of an object’s attributes constitute
calculateAmount() the state of the object. For example, attributes of a paycheck
writeCheck() include its payee and monetary value, and the state of those
cashCheck() attributes might be Alice Nelson and $400. The behaviors of
an object are the things it “does,” or its methods; for example,
Figure 1-1 A diagram for
a paycheck object can be written and cashed, and contains a
a Paycheck
method to calculate the check amount. Figure 1-1 shows how
a programmer might start to visualize a paycheck—thinking about its name, attributes, and
behaviors. Beyond a paycheck, object-oriented programmers might design a payroll system
by thinking about all the additional objects needed to produce a paycheck, such as employees,
time cards, and bank accounts.

Programmers use the term OO, pronounced “oh oh,” as an abbreviation for object oriented. When discussing
object-oriented programming, they use OOP, which rhymes with soup. Examples of OO languages include
C#, Java, Visual Basic, and C++. You can write procedural programs in OO languages, but you cannot write
OO programs in procedural languages.

Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-202
CHAPTER 1 A First Program Using C#

With either approach, procedural or object-oriented, you can produce a correct paycheck,
and both techniques employ reusable program modules. The major difference lies in the
focus the programmer takes during the earliest planning stages of a project. Taking an
object-oriented approach to a problem means defining the objects needed to accomplish
a task and developing classes that describe the objects so that each object maintains its
6
own data and carries out tasks when another object requests them. The object-oriented
approach is said to be “natural”—it is more common to think of a world of objects and the
ways they interact than to consider a world of systems, data items, and the logic required to
manipulate them.

Object-oriented programming employs a large vocabulary; you can learn much of this terminology in the
chapter called “Using Classes and Objects.”

Originally, object-oriented programming was used most frequently for two major types of
applications:
•• Computer simulations are programs that attempt to mimic real-world activities so that
their processes can be improved or so that users can better understand how the real-world
processes operate.
•• Graphical user interfaces, or GUIs (pronounced gooeys) are programs that allow users to
interact with a program in a graphical environment, such as by clicking with a mouse or
using a touch screen.
Thinking about objects in these two types of applications makes sense. For example, a city
might want to develop a program that simulates traffic patterns to better prevent congestion.
By creating a model with objects such as cars and pedestrians that contain their own data
and rules for behavior, the simulation can be set in motion. For example, each car object has
a specific current speed and a procedure for changing that speed. By creating a model of city
traffic using objects, a computer can create a simulation of a real city at rush hour. Creating
a GUI environment for users also is a natural use for object orientation. It is easy to think of
the components a user manipulates on a computer screen, such as buttons and scroll bars,
as similar to real-world objects. Each GUI object contains data—for example, a button on
a screen has a specific size and color. Each object also contains behaviors—for example,
each button can be clicked and reacts in a specific way when clicked. Some people consider
the term object-oriented programming to be synonymous with GUI programming, but ­
object-oriented programming means more. Although many GUI programs are object
oriented, one does not imply the other. Modern businesses use object-oriented design
techniques when developing all sorts of business applications, regardless of whether they
are GUI applications.

Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-202
Features of Object-Oriented Programming Languages 

TWO TRUTHS & A LIE


Procedural and Object-Oriented Programming
1. Procedural programs use variables and tasks that are grouped into methods or 7
procedures.
2. Object-oriented programming languages do not support variables or methods; instead
they focus on objects.
3. Object-oriented programs were first used for simulations and GUI programs.

methods just as procedural programs do.


The false statement is #2. Object-oriented programs contain variables and

Features of Object-Oriented Programming Languages


For a language to be considered object-oriented, it must support the following features:
•• Classes
•• Objects
•• Encapsulation and interfaces
•• Inheritance
•• Polymorphism
A class describes potential objects, including their attributes and behaviors. A class is similar
to a recipe or a blueprint in that it describes what features objects will have and what they
will be able to do after they are created. An object is an instance of a class; it is one tangible
example of a class.
For example, you might create a class named Automobile. Some of an Automobile’s attributes
are its make, model, year, and purchase price. All Automobiles possess the same attributes,
but not the same values, or states, for those attributes. (Programmers also call the values of an
object’s attributes the properties of the object.) When you create specific Automobile objects,
each object can hold unique values for the attributes, such as Ford, Taurus, 2018, and $27,000.
Similarly, a Dog has attributes that include its breed, name, age, and vaccination status; the
attributes for a particular dog might be Labrador retriever, Murphy, 7, and current.
When you understand that an object belongs to a specific class, you know a lot about the object.
If your friend purchases an Automobile, you know it has some model name; if your friend gets a
Dog, you know it has some breed. You probably don’t know the current state of the Automobile’s

Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-202
CHAPTER 1 A First Program Using C#

speed or of the Dog’s shots, but you do know that those attributes exist for the Automobile and
Dog classes. Similarly, in a GUI operating environment, you expect each window you open to
have specific, consistent attributes, such as a menu bar and a title bar, because each window
includes these attributes as a member of the general class of GUI windows.
8 By convention, programmers using C# begin their class names with an uppercase letter and use a singular
noun. Thus, the class that defines the attributes and methods of an automobile would probably be named
Automobile, and the class that contains dogs would probably be named Dog. If the class requires two
words, programmers conventionally use upper camel casing, as in BankAccount.

Besides attributes, objects possess methods that they use to accomplish tasks, including
changing attributes and discovering the values of attributes. Automobiles, for example, have
methods for moving forward and backward. They also can be filled with gasoline or be washed;
both are methods that change some of an Automobile’s attributes. Methods also exist for
determining the status of certain attributes, such as the current speed of an Automobile and
the number of gallons of gas in its tank. Similarly, a Dog can walk or run, eat, and get a bath,
and there are methods for determining whether it needs a walk, food, or a bath. GUI operating
system components, such as windows, can be maximized, minimized, and dragged; depending
on the component, they also can have their color or font style altered.
Like procedural programs, object-oriented programs have variables (attributes) and procedures
(methods), but the attributes and methods are encapsulated into objects that then are used
much like real-world objects. Encapsulation is the technique of packaging an object’s attributes
and methods into a cohesive unit that can be used as an undivided entity. Programmers
sometimes refer to encapsulation as using a black box, a device you use without regard for the
internal mechanisms. If an object’s methods are well written, the user is unaware of the low-
level details about how the methods are executed; in such a case, the user must understand
only the interface or interaction between the method and object. For example, if you can fill
your Automobile with gasoline, it is because you understand the interface between the gas
pump nozzle and the vehicle’s gas tank opening. You don’t need to understand how the pump
works or where the gas tank is located inside your vehicle. If you can read your speedometer, it
does not matter how the display value is calculated. In fact, if someone produces a new, more
accurate speedometer and inserts it into your Automobile, you don’t have to know or care how
it operates, as long as the interface remains the same as the previous one. The same principles
apply to well-constructed objects used in object-oriented programs.
Object-oriented programming languages support two other distinguishing features in addition
to organizing objects as members of classes. One feature, inheritance, provides the ability
to extend a class so as to create a more specific class. The more specific class contains all
the attributes and methods of the more general class and usually contains new attributes or
methods as well. For example, if you have created a Dog class, you might then create a more
specific class named ShowDog. Each instance of the ShowDog class would contain, or inherit,
all the attributes and methods of a Dog, along with additional methods or attributes. For
example, a ShowDog might require an attribute to hold the number of ribbons won and a
method for entering a dog show. The advantage of inheritance is that when you need a class
such as ShowDog, you often can extend an existing class, thereby saving a lot of time and work.
Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-202
The C# Programming Language 

Object-oriented languages also support polymorphism, which is the ability to create methods
that act appropriately depending on the context. That is, programs written in object-oriented
languages can distinguish between methods with the same name based on the type of object
that uses them. For example, you are able to “fill” both a Dog and an Automobile, but you do
so by very different means. Similarly, the procedure to “fill” a ShowDog might require different
9
food than that for a “plain” Dog. Older, non-object-oriented languages could not make such
distinctions, but object-oriented languages can.
The chapters “Using Classes and Objects” and “Introduction to Inheritance” contain much more information
about the features of object-oriented programs.

Watch the video Object-Oriented Programming.

TWO TRUTHS & A LIE


Features of Object-Oriented Programming Languages
1. Object-oriented programs contain classes that describe the attributes and methods of
objects.
2. Object-oriented programming languages support inheritance, which refers to the
packaging of attributes and methods into logical units.
3. Object-oriented programming languages support polymorphism, which is the ability of
a method to act appropriately based on the context.

specific ones. Encapsulation refers to the packaging of attributes and methods.


The false statement is #2. Inheritance is the ability to extend classes to make more

The C# Programming Language


The C# programming language was developed as an object-oriented and component-
oriented language. It is part of Microsoft Visual Studio, a package designed for developing
applications that run on Windows computers. (The newest version of C# is C# 7.0; the version
number tells you there were six major versions prior to the most recent release.) Unlike
other programming languages, C# allows every piece of data to be treated as an object and to
consistently employ the principles of object-oriented programming. C# provides constructs
for creating components with properties, methods, and events, making it an ideal language
for modern programming, where building small, reusable components is more important
than building huge, stand-alone applications. You can find Microsoft’s C# specifications at
msdn.microsoft.com. Search for C# specifications.
Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-202
CHAPTER 1 A First Program Using C#

If you have not programmed before, the differences between C# and other languages mean
little to you. However, experienced programmers will appreciate the thought that was put into
C# features. For example:
•• C# contains a GUI interface that makes it similar to Visual Basic, but C# is considered more
10 concise than Visual Basic.
•• C# is modeled after the C++ programming language, but is considered easier to learn. Some
of the most difficult features to understand in C++ have been eliminated in C#.

Some differences between C# and C++ are that pointers (variables that hold memory addresses) are
not used in C# (except in a mode called unsafe, which is rarely used), object destructors and forward
declarations are not needed, and using #include files is not necessary. Multiple inheritance, which causes
many C++ programming errors, is not allowed in C#.

•• C# is very similar to Java, because Java was also based on C++. However, C# is more truly
object oriented. Unlike in Java, every piece of data in C# is an object, providing all data with
increased functionality.

In Java, simple data types are not objects; therefore, they do not work with built-in methods. Additionally,
in Java, data can only be passed to and from methods using a copy; C# omits this limitation. You will learn
more in two later chapters: “Using Methods” and “Advanced Method Concepts.”

The C# programming language was standardized in 2002 by Ecma International. You can read or download
this set of standards at www.ecma-international.org/publications/standards/Ecma-334.htm.

TWO TRUTHS & A LIE


The C# Programming Language
1. The C# programming language was developed as an object-oriented and component-
oriented language.
2. C# contains several features that make it similar to other languages such as Java and
Visual Basic.
3. C# contains many advanced features, so the C++ programming language was created
as a simpler version of the language.

some of the most difficult features to understand in C++ have been eliminated in C#.
The false statement is 3. C# is modeled after the C++ programming language, but

Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-202
Writing a C# Program that Produces Output 

Writing a C# Program that Produces Output


At first glance, even the simplest C# program involves a fair amount of confusing syntax.
Consider the simple program in Figure 1-2. This program is written on seven lines, and its only
task is to display This is my first C# program on the screen.
11

class FirstClass
{
static void Main()
{
System.Console.WriteLine("This is my first C# program");
}
}

Figure 1-2 FirstClass console application

The statement that does the actual work in this program is in the middle of the figure:
System.Console.WriteLine("This is my first C# program");

The statement ends with a semicolon because all C# statements do.


The text "This is my first C# program" is a literal string of characters—that is, a series
of characters that will be used exactly as entered. Any literal string in C# appears between
double quotation marks.
The string "This is my first C# program" appears within parentheses because the string
is an argument to a method, and arguments to methods always appear within parentheses.
Arguments represent information that a method needs to perform its task. For example, if
making an appointment with a dentist’s office was a C# method, you would write the following:
MakeAppointment("September 10", "2 p.m.");

Accepting and processing a dental appointment is a method that consists of a set of standard
procedures. However, each appointment requires different information—the date and time—
and this information can be considered the arguments of the MakeAppointment() method.
If you make an appointment for September 10 at 2 p.m., you expect different results than if
you make one for September 9 at 8 a.m. or December 25 at midnight. Likewise, if you pass the
argument "Happy Holidays" to a method, you will expect different results than if you pass
the argument "This is my first C# program".

Although an argument to a method might be a string, not all arguments are strings. In this book, you will see
and write methods that accept many other types of data.

Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-202
CHAPTER 1 A First Program Using C#

Within the following statement, the method to which you are passing the argument string is
named WriteLine():
System.Console.WriteLine("This is my first C# program");

The WriteLine() method is a built-in method that is part of the C# language, and it displays
12 output on the screen and positions the cursor on the next line, where additional output might
subsequently be displayed. The Write() method is very similar to the WriteLine() method.
With WriteLine(), the cursor moves to the following line after the message is displayed. With
Write(), the cursor does not advance to a new line; it remains on the same line as the output.
Within the following statement Console is a class that contains the WriteLine() method:
System.Console.WriteLine("This is my first C# program");

Of course, not all classes have a WriteLine() method (for instance, you can’t write a line
to a computer’s mouse, an Automobile, or a Dog), but the creators of C# assumed that you
frequently would want to display output on the screen at your terminal. For this reason, the
Console class was created and endowed with the method named WriteLine(). When you use
the WriteLine() method, programmers say that you call it or invoke it. Soon, you will create
your own C# classes and endow them with your own callable methods. Within the following
statement, System is a namespace:
System.Console.WriteLine("This is my first C# program");

A namespace is a construct that acts like a container to provide a way to group similar
classes. To organize your classes, you can (and will) create your own namespaces. The System
namespace, which is built into your C# compiler, holds commonly used classes.

An advantage to using Visual Studio is that all of its languages use the same namespaces. In other words,
everything you learn about any namespace in C# is knowledge you can transfer to Visual C++ and Visual
Basic.

The dots (periods) in the phrase System.Console.WriteLine are used to separate the names
of the namespace, class, and method. You will use this same namespace-dot-class-dot-method
format repeatedly in your C# programs.
In the FirstClass class in Figure 1-2, the WriteLine() statement appears within a method
named Main(). Every executable C# application must contain a Main() method because that is
the starting point for every program. As you continue to learn C# from this book, you will write
applications that contain additional methods. You also will create classes that are not programs,
and so do not need a Main() method. For example, a Dog or Automobile class would not be
a program. Rather they would be classes from which objects are created, and, in turn, those
objects would be used in programs with a Main() method.

Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-202
Writing a C# Program that Produces Output 

Every method in C# contains a header and a body. A method header includes the method
name and information about what will pass into and be returned from a method. A method
body is contained within a pair of curly braces ( { } ) and includes all the instructions executed
by the method. The program in Figure 1-2 includes only one statement between the curly
braces of the Main() method. Soon, you will write methods with many more statements.
13
In Figure 1-2, the WriteLine()statement within the Main() method is indented within the
curly braces. Although the C# compiler does not require such indentation, it is conventional
and clearly shows that the WriteLine() statement lies within the Main() method.

Do not confuse curly braces with parentheses. Curly braces have a small bump in the middle while
parentheses are smooth. The left and right curly braces are located on most PC keyboards to the right of
the letter p above the brackets, and the left and right parentheses are located on the number keys at the top
of the keyboard above the 9 and 0. The curly braces and parentheses have separate, specific uses in C#,
and a syntax error is created if you use the incorrect pair.

For every opening curly brace ( { ) that encloses a method’s statements in a C# program, there
must be a corresponding closing curly brace ( } ). The precise position of the opening and
closing curly braces is not important to the compiler. In general, whitespace is optional in C#.
Whitespace is any combination of spaces, tabs, and carriage returns (blank lines). You use
whitespace to organize your program code and make it easier to read; it does not affect your
program’s execution. Usually, you vertically align each pair of opening and closing curly braces
and indent the contents between them, as shown in Figure 1-2.
The method header for the Main() method in Figure 1-2 contains three words. Two of these
words (static and void) are keywords. In this book, C# keywords appear in bold. A complete
list of keywords appears in Table 1-1 later in this chapter. In the method header static void
Main(), the keyword static indicates that the Main() method will be executed through a
class—not by a variety of objects. It means that you do not need to create an object of type
FirstClass to use the Main() method defined within FirstClass. Later in this book, you
will create other methods that are nonstatic methods and that are executed by objects.
The second word in the method header in Figure 1-2 is void. In English, the word void
means empty or having no effect. When the keyword void is used in the Main() method
header, it does not indicate that the Main() method is empty, or that it has no effect, but rather
that the method does not return any value when called. You will learn more about methods
that return values (and do affect other methods) when you study methods in greater detail. In
the method header, the name of the method is Main(). Main() is not a C# keyword, but all
C# applications must include a method named Main(), and most C# applications will have
additional methods with other names. Recall that when you execute a C# application, the
Main() method always executes first. Classes that contain a Main() method are application
classes. Applications are executable or runnable. Classes that do not contain a Main()
method are non-application classes, and are not runnable. Non-application classes provide
support for other classes.

Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-202
CHAPTER 1 A First Program Using C#

Watch the video The Parts of a C# Program.

14
TWO TRUTHS & A LIE
Writing a C# Program that Produces Output
1. Strings are information that methods need to perform their tasks.
2. The WriteLine() method displays output on the screen and positions the cursor on
the next line, where additional output might be displayed.
3. Many methods such as WriteLine() have been created for you because the creators
of C# assumed you would need them frequently.

Although an argument might be a string, not all arguments are strings.


marks. Arguments represent information that a method needs to perform its task.
The false statement is #1. Strings are literal values represented between quotation

Selecting Identifiers
Every method that you use within a C# program must be part of a class. To create a class, you
use a class header and curly braces in much the same way you use a header and braces for a
method within a class. When you write class FirstClass, you are defining a class named
FirstClass. A class name does not have to contain the word Class as FirstClass does; as
a matter of fact, most class names you create will not contain Class. You can define a C# class
using any identifier you need, as long as it meets the following requirements:
•• An identifier must begin with an underscore, the “at” sign ( @ ), or a letter. Letters include
foreign-alphabet letters such as П and Ω, which are contained in the set of characters known
as Unicode. You will learn more about Unicode in the next chapter.
•• An identifier can contain only letters, digits, underscores, and the @ sign. An identifier
cannot contain spaces or any other punctuation or special characters such as #, $, or &.
•• An identifier cannot be a C# reserved keyword, such as class or void. Table 1-1 provides
a complete list of reserved keywords. Actually, you can use a keyword as an identifier if
you precede it with an @ sign, as in @class. An identifier with an @ prefix is a verbatim
identifier. This feature allows you to use code written in other languages that do not have
the same set of reserved keywords. However, when you write original C# programs, you
should not use the keywords as identifiers.

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

abstract float return


as for sbyte
base foreach sealed
bool goto short 15

break if sizeof
byte implicit stackalloc
case in static
catch int string
char interface struct
checked internal switch
class is this
const lock throw
continue long true
decimal namespace try
default new typeof
delegate null uint
do object ulong
double operator unchecked
else out unsafe
enum override ushort
event params using
explicit private virtual
extern protected void
false public volatile
finally readonly while
fixed ref

Table 1-1 C# reserved keywords

The following identifiers have special meaning in C# but are not keywords: add, alias, get,
global, partial, remove, set, value, where, and yield. For clarity, you should avoid using
these words as your own identifiers.

Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-202
CHAPTER 1 A First Program Using C#

Table 1-2 lists some valid and conventional class names you might use when creating classes in
C#. You should follow established conventions for C# so that other programmers can interpret
and follow your programs. Table 1-3 lists some class names that are valid, but unconventional;
Table 1-4 lists some illegal class names.
16
Class Name Description
Employee Begins with an uppercase letter

FirstClass Begins with an uppercase letter, contains no spaces, and has an initial
uppercase letter that indicates the start of the second word

PushButtonControl Begins with an uppercase letter, contains no spaces, and has an initial
uppercase letter that indicates the start of all subsequent words

Budget2016 Begins with an uppercase letter and contains no spaces

Table 1-2 Some valid and conventional class names in C#

Class Name Description


employee Unconventional as a class name because it begins with a lowercase letter

First_Class Although legal, the underscore is not commonly used to indicate new
words in class names

Pushbuttoncontrol No uppercase characters are used to indicate the start of a new word,
making the name difficult to read

BUDGET2016 Unconventional as a class name because it contains all uppercase letters

Void Although this identifier is legal because it is different from the keyword
void, which begins with a lowercase v, the similarity could cause confusion

Table 1-3 Some unconventional (though legal) class names in C#

Class Name Description


an employee Space character is illegal

Push Button Control Space characters are illegal

class class is a reserved word

2016Budget Class names cannot begin with a digit

phone# The # symbol is not allowed; identifiers consist of letters, digits,


underscores, or @

Table 1-4 Some illegal class names in C#

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

In Figure 1-2, the line class FirstClass contains the keyword class, which identifies
FirstClass as a class.
The simple program shown in Figure 1-2 has many pieces to remember. For now, you
can use the program shown in Figure 1-3 as a shell, where you replace the identifier
AnyLegalClassName with any legal class name, and the line /*********/ with any statements 17
that you want to execute.

class AnyLegalClassName
{
static void Main()
{
/*********/;
}
}

Figure 1-3 Shell program

Watch the video C# Identifiers.

TWO TRUTHS & A LIE


Selecting Identifiers
1. In C#, an identifier must begin with an underscore, the at sign ( @ ), or an uppercase
letter.
2. An identifier can contain only letters, digits, underscores, and the @ sign, not special
characters such as #, $, or &.
3. An identifier cannot be a C# reserved keyword.

capitalized.
although in C#, it is a convention that the initial letter of a class name is
@ sign, or a letter. There is no requirement that the initial letter be capitalized,
The false statement is #1. In C#, an identifier must begin with an underscore, the

Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-202
CHAPTER 1 A First Program Using C#

Improving Programs by Adding Comments


and Using the System Namespace
As you can see, even the simplest C# program takes several lines of code and contains
18
somewhat perplexing syntax. Large programs that perform many tasks include much more
code. As you work through this book, you will discover many ways to improve your ability to
handle large programs. Two things you can do immediately are to add program comments and
use the System namespace.

Adding Program Comments


As you write longer programs, it becomes increasingly difficult to remember why you included
steps and how you intended to use particular variables. Program comments are nonexecuting
statements that you add to document a program. Programmers use comments to leave notes
for themselves and for others who might read their programs.

As you work through this book, you should add comments as the first few lines of every program file. The
comments should contain your name, the date, and the name of the program. Your instructor might want
you to include additional comments.

Comments also can be useful when you are developing a program. If a program is not
performing as expected, you can comment out various statements and subsequently run
the program to observe the effect. When you comment out a statement, you turn it into a
comment so the compiler will ignore it. This approach helps you pinpoint the location of errant
statements in malfunctioning programs.
C# offers three types of comments:
•• Line comments start with two forward slashes ( // ) and continue to the end of the current
line. Line comments can appear on a line by themselves, or they can occupy part of a line
following executable code.
•• Block comments start with a forward slash and an asterisk ( /* ) and end with an asterisk
and a forward slash ( */ ). Block comments can appear on a line by themselves, on a line
before executable code, or after executable code. When a comment is long, block comments
can extend across as many lines as needed.
•• C# also supports a special type of comment used to create documentation within a program:
XML-documentation format comments use a special set of tags within angle brackets
( < > ). (XML stands for Extensible Markup Language.) You will learn more about this type
of comment as you continue your study of C#.

The forward slash ( / ) and the backslash ( \ ) characters often are confused, but they are distinct
characters. You cannot use them interchangeably.

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

Figure 1-4 shows how comments can be used in code. The program covers 10 lines, yet only
seven are part of the executable C# program, including the last two lines, which contain curly
braces and are followed by partial-line comments. The only line that actually does anything
visible when the program runs is the shaded one that displays Message.
19

/* This program is written to demonstrate using comments


*/
class ClassWithOneExecutingLine
{
static void Main()
{
// The next line writes the message
System.Console.WriteLine(“Message");
} // End of Main
} //    End of ClassWithOneExecutingLine

Figure 1-4 Using comments within a program

Using the System Namespace


A program can contain as many statements as you need. For example, the program in
Figure 1-5 produces the three lines of output shown in Figure 1-6. (To get the output, you
have to know how to compile and execute the program, which you will learn in the next
part of this chapter.) A semicolon separates each program statement.

class ThreeLinesOutput
{
static void Main()
{
System.Console.WriteLine("Line one");
System.Console.WriteLine("Line two");
System.Console.WriteLine("Line three");
}
}

Figure 1-5 A program that produces three lines of output

Figure 1-6 Output of the ThreeLinesOutput program


Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-202
CHAPTER 1 A First Program Using C#

Figure 1-6 shows the output of the ThreeLinesOutput program when it is run in Visual Studio. The prompt
to Press any key to continue is not part of the program; it is added by Visual Studio, but it does not appear if
you run the program from the command prompt.

20 The program in Figure 1-5 shows a lot of repeated code—the phrase System.Console.
WriteLine appears three times. When you need to repeatedly use a class from the same
namespace, you can shorten the statements you type by adding a clause that indicates a
namespace containing the class. You indicate a namespace with a using clause, or using
directive, as shown in the shaded statement in the program in Figure 1-7. If you type using
System; prior to the class definition, the compiler knows to use the System namespace when
it encounters the Console class. The output of the program in Figure 1-7 is identical to that in
Figure 1-5, in which System was repeated with each WriteLine() statement.

using System;
class ThreeLinesOutput
{
static void Main()
{
Console.WriteLine("Line one");
Console.WriteLine("Line two");
Console.WriteLine("Line three");
}
}

Figure 1-7 A program that produces three lines of output with a using System; clause

Although it was not an option in older versions of C#, now you can reduce typing in programs
even further by inserting using static System.Console; at the top of a program. So, the
program in Figure 1-8 uses only the method name WriteLine() in its output statements, and
the program works correctly, (You have already seen the word static in the Main() method
header. Recall that static means a method is used without creating an object. In Chapter 7,
you will learn more about the use of the keyword static.) The simpler style shown in
Figure 1-8 is the style used for programs in the rest of this book.

using static System.Console;


class ThreeLinesOutput
{
static void Main()
{
WriteLine("Line one");
WriteLine("Line two");
WriteLine("Line three");
}
}

Figure 1-8 A program that produces three lines of output with a using static System.Console; clause

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

TWO TRUTHS & A LIE

Improving Programs by Adding Comments


and Using the System Namespace 21
1. Line comments start with two forward slashes ( // ) and end with two backslashes ( \\ ).
2. Block comments can extend across as many lines as needed.
3. You use a namespace with a using clause, or using directive, to shorten statements
when you need to repeatedly use a class from the same namespace.

continue to the end of the current line.


The false statement is #1. Line comments start with two forward slashes ( // ) and

You Do It

Now that you understand the basic framework of a program written in C#, you
are ready to enter your first C# program into a text editor. It is a tradition among
programmers that the first program you write in any language produces Hello, world!
as its output. To create a C# program, you can use any simple text editor, such as
Notepad, or the editor that is included as part of Microsoft Visual Studio. There are
advantages to using the C# editor to write your programs, but using a plain text
­editor is simpler when you are getting started.

Entering a Program into an Editor

1. Start any text editor, such as Notepad, and open a new document,
if necessary.
2. Type the using statement and the header for the class:
using static System.Console;
class Hello
3. On the next two lines, type the class-opening and class-closing curly braces: {}.
Some programmers type a closing brace as soon as they type the opening one
to guarantee that they always type complete pairs.
(continues)

Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-202
CHAPTER 1 A First Program Using C#

(continued)

4. Between the class braces, insert a new line, type three spaces to indent, and
22
write the Main() method header:
static void Main()
5. On the next two lines, type the opening and closing braces for the Main()
method, indenting them about three spaces.
6. Between the Main() method’s braces, insert a new line and type six spaces
so the next statement will be indented within the braces. Type the one
executing statement in this program:
WriteLine("Hello, world!");
Your code should look like Figure 1-9.

using static System.Console;


class Hello
{
static void Main()
{
WriteLine("Hello, world!");
}
}

Figure 1-9 The Hello class

7. Choose a location that is meaningful to you to save your program.


For example, you might create a folder named CSharp on your hard drive.
Within that folder, you might create a folder named Chapter01 in which you
will store all the examples and exercises in this chapter. If you are working
in a school lab, you might be assigned a storage location on your school’s
server. Save the program as Hello.cs. It is important that the file extension
be .cs, which stands for C Sharp. If the file has a different extension, the
compiler for C# will not recognize the program as a C# program.

Many text editors attach their own filename extension (such as .txt or .doc) to a saved file. Double-
check your saved file to ensure that it does not have a double extension (as in Hello.cs.txt). If the
file has a double extension, rename it. If you use a word-processing program as your editor, select
the option to save the file as a plain text file.

Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-202
Compiling and Executing a C# Program 

Compiling and Executing a C# Program


After you write and save a program, two more steps must be performed before you can view
the program output:
1. You must compile the program you wrote (the source code) into intermediate 23
language (IL) .
2. The C# just in time (JIT) compiler must translate the intermediate code into
executable code.
When you compile a C# program, your source code is translated into intermediate
language. The JIT compiler converts IL instructions into native code at the last moment,
and appropriately for each type of operating system on which the code eventually might
be executed. In other words, the same set of IL can be JIT compiled and executed on any
supported architecture.

Some developers say that languages such as C# are “semi-compiled.” That is, instead of being translated
immediately from source code to their final executable versions, programs are compiled into an intermediate
version that is later translated into the correct executable statements for the environment in which the
program is running.

You can write a program using a simple editor such as Notepad and then perform these steps
from the command prompt in your system. You also can write a program within the Integrated
Development Environment that comes with Visual Studio. Both methods can produce the
same output; the one you use is a matter of preference.
•• The command line is the line on which you type a command in a system that uses a text
interface. The command prompt is a request for input that appears at the beginning of the
command line. In DOS, the command prompt indicates the disk drive and optional path,
and ends with >. When you install Microsoft Visual Studio on a computer, you get access
to the Developer Command Prompt which is a special version of the command prompt
for which specific settings have been enabled so that you can easily compile and run C#
programs. (You could enact these settings yourself from the command prompt built-in with
Windows; it just would be more work.) You might prefer the simplicity of the developer
command prompt because you do not work with multiple menus and views as you do when
you use the Integrated Development Environment. (Additionally, as you continue to study
advanced features of C#, you might want to pass command-line arguments to a program. If
so, you must compile from the command line.)
•• The Integrated Development Environment (IDE) is a programming environment that
allows you to issue commands by selecting choices from menus and clicking buttons.
The IDE operates more like other software you may have used, such as a word processing
program or spreadsheet. Many programmers prefer using the IDE because it provides
features such as color-coded keywords and automatic statement completion.

Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-202
Other documents randomly have
different content
hoped to be ancestor, never appeared, for the king was childless,
and soon made an enemy of his father-in-law. Some people say that
Godwine did not treat his royal son with much respect having once
put him on the throne. Eadward too never was able to forget the
suspicion about Ælfred's murder, so the breach between him and the
great earl was widened year by year. Eadward was not the sturdy
English monarch for whom his people had hoped; he was Norman at
heart, as a man might well be who had learned to speak in the
foreign tongue, and had made the friendships of his [Pg189] boyhood
and manhood in the duke's court and cloisters. Priestcraft was
dearer to him than statecraft, and his name of The Confessor
showed what almost saintly renown he had won from those who
were his friends and upholders.
It did not suit very well that one Norman gentleman after
another came to London to fill some high official position. Eadward
appeared to wish to surround himself wholly with Normans, and the
whole aspect of the English court was changed little by little. The
king proved his own weakness in every way—he was as like
Æthelred the Unready as a good man could be like a bad one.
Godwine grew more and more angry, and his determination to
show that England could do without the crowds of interlopers who
were having every thing their own way worked him disaster for a
time. There was a party of the king's friends journeying homeward
to Normandy, who stopped overnight in the city of Dover and
demanded its hospitality in insolent fashion. The Dover men would
not be treated like slaves, and a fight followed in which the
Frenchmen were either killed or driven out of the town. Eadward of
course sided with his friends, and was very indignant; he sent orders
to Earl Godwine, who was governor of the region, to punish the
offenders, but Godwine refused squarely unless the men should
have been fairly tried and given a chance to speak for themselves.
This ended in a serious quarrel, and the king gained a victory
without any battle either, for there was a sudden shifting of public
feeling in Eadward's favor—Godwine's own men forsook him [Pg190]
and were loyal to the crown, and the great earl was banished for
conscience sake, he and all his family, for the king even sent away
his own wife, though he kept all her lands and treasures, which was
not so saint-like and unworldly as one might have expected. One of
Godwine's sons had proved himself a very base and treacherous
man, and the earl had shielded him; this was one reason why his
defence of English liberty was so overlooked by his countrymen, but
the Normans had a great triumph over this defeat, and praised the
pious king and told long stories of his austere life, his prayers, and
holy life. After he was canonized these stories were lengthened still
more, but while he was yet without a halo some of his
contemporaries charge him with laziness and incapacity. He certainly
was lacking in kingly qualities, but he gained the respect and love of
many of his subjects, and was no doubt as good as so weak a man
could be. After his death Englishmen praised him the more because
they liked William the Conqueror the less, and as for the Normans
they liked anybody better than Harold, who had been a much more
formidable opponent in his claim to the English crown. Mr. Freeman
says: "—————— The duties of secular government ... were ...
always something which went against the grain. His natural place
was not on the throne of England, but at the head of a Norman
abbey.... For his virtues were those of a monk; all the real man came
out in his zeal for collecting relics, in his visions, in his religious
exercises, in his gifts to churches and monasteries, in his desire to
mark his [Pg191] reign as its chief result, by the foundation of his great
abbey of Saint Peter at Westminster. In a prince of the manly piety
of Ælfred things of this sort form only a part, a pleasing and
harmonious part, of the general character. In Eadward they formed
the whole man."
The chronicler who writes most flatteringly of him acknowledges
that he sometimes had shocking fits of bad temper, but that he was
never betrayed into unbecoming language. On some occasions he
was hardly held back by Godwine or Harold from civil war and
massacre; though he was conscientious within the limit of his
intelligence, and had the art of giving a gracious refusal and the
habit of affability and good manners. William of Malmesbury, the
chronicler, tells us that he kept his royal dignity, but that he took no
pleasure in wearing his robes of state, even though they were
worked for him by his affectionate queen. Like his father, he was
ever under the dominion of favorites, and this was quickly enough
discovered and played upon by Norman ecclesiastics and Norman
and Breton gentlemen in search of adventure and aggrandizement.
It makes a great difference whether we read the story of this time in
English or in French records. Often the stories are directly opposite
to each other, and only the most careful steps along the path keep
one from wandering off one way or the other into unjust
partisanship. Especially is this true of Godwine, the confessor's great
contemporary. He seems, at any rate, to have been a man much
ahead of his time in knowledge of affairs and foresight of the
probable effects [Pg192] from the causes of his own day. His brother
earls were jealous of him; the Church complained of his lack of
generosity; even his acknowledged eloquence was listened to
incredulously; and his good government of his own provinces,
praised though it was, did not gain him steady power. His good
government made him, perhaps more than any thing else, the
foremost Englishman of his time, and presently we shall see how
deep a feeling there was for him in England, and how much
confidence and affection were shown in his welcome back from
exile, though he had been allowed to go away with such sullen
disapproval. Godwine's wife, Gytha, was a Danish woman, which
was probably a closer link with that faction in the northern earldom
than can be clearly understood at this late day. Lord Lytton's novel,
called "Harold," makes this famous household seem to live before
our eyes, and the brief recital of its fortunes and conditions here
cannot be more than a hint of the real romance and picturesqueness
of the story.
The absence of Godwine in Flanders—a whole year's absence—
had taught his countrymen what it was to be without him. They
were sadly annoyed and troubled by the king's continued
appointment of Normans to every place of high honor that fell
vacant. Bishoprics and waste lands alike were pounced upon by the
hangers-on at court, and castles were lifting their ugly walls within
sight of each other almost, here and there in the quiet English fields.
Even in London itself the great White Tower was already setting its
strong foundations; [Pg193] a citadel for the town, a fort to keep the
borderers and Danes at bay were necessary enough to a country,
but England was being turned into another Normandy and Brittany,
with these new houses that were built for war, as if every man's
neighbor were his enemy. The square high towers were no fit places
for men to live in who tilled the soil and tended their flocks and
herds. There were too many dark dungeons provided among the
foundation stones beside, and the English farmers whispered
together about their new townsfolk and petty lords, and feared the
evil days that were to come.
The ruined Roman houses and strange tall stones of the Druid
temples were alike thrown down and used to build these new
castles. Men who had strayed as far as the Norman coasts had
stories enough to tell; what landmarks of oppression these same
castles were in their own country, and how the young Duke William
had levelled many of them to the ground in quarrelsome Normandy.
There was no English word for this awesome new word—castles!
The free and open halls of the English thanes were a strange
contrast to the new order of dwelling-places. Robert of Jumièges had
been made Archbishop of Canterbury, and a host of his countrymen
surrounded the king more and more closely and threatened to
deprive the English of their just rights. It was this monk Robert who
had "beat into the king's head" that his brother Ælfred had come to
his death through Earl Godwine.
It is very easy to tell the story of the Normans from the English
side. Let us cross the Channel again [Pg194] to Rouen and see what
effect the condition of English affairs was having upon the young
duke. It would not be strange if his imagination were busy with
some idea of enlarging his horizon by a look at his neighbors.
Eadward had no heir, they had talked together oftentimes, perhaps,
about the possibility of making one noble great kingdom by the
joining of England and Normandy. Every day more stories reached
his ears of the wealth and fruitfulness of the Confessor's kingdom.

[Pg195]
X.
THE BATTLE OF VAL-ÈS-DUNES.
"Who stood with head erect and shining eyes,
As if the beacon of some promised land
Caught his strong vision, and entranced it there."
—A. F.

The Viking's grandchildren had by no means lost their TOC, INDX


love for journeying by land or sea. As in old Norway one
may still find bits of coral and rudely shaped precious stones set in
the quaintly wrought silver ornaments made by the peasants, so in
Normandy there are pieces of Spanish leather and treasures from
the east and from the south, relics of the plundering of a later
generation. Roger de Toesny, one of William's fiercest enemies, does
not become well-known to us until we trace out something of his
history as a wanderer before he came to join Talvas in a well-
planned rebellion.
In Duke Richard the Good's time there was a restless spirit of
adventure stirring in Norman hearts, and the foundations were laid
of the Southern kingdoms which made such a change in Europe. A
Norman invasion of Spain came to nothing in comparison with those
more important settlements, but in 1018 Roger de Toesny carried
the Norman [Pg196] arms into the Spanish peninsula. A long time
before this Richard the Fearless had persuaded a large company of
his Scandinavian subjects to wander that way, being pagan to the
heart's-core and hopelessly inharmonious. Roger followed them on a
grand crusade against the infidel Saracen, and also hoped to gain a
kingdom for himself. He was of the noblest blood in Normandy, of
Rolf the Ganger's own family, and well upheld the warlike honor of
his house in his daring fights with the infidel. Almost unbelievable
stories are told of his cannibal-like savagery with his captives, but
the very same stories are told of another man, so we will not stop to
moralize upon Roger's wickedness. He married the Spanish countess
of Barcelona, who did homage to the king of France, and every thing
looked prosperous at one time for his dominion, but it never really
took root after all, and de Toesny went back again to Normandy, and
blazed out instantly with tremendous wrath at the pretentions of
William the Bastard. He could not believe that the proud Norman
barons and knights would ever submit to such a degradation. De
Talvas was only too glad to greet so sympathetic an ally, and the
opposition to the young duke took a more formidable shape than
ever before.
All through William's earliest years the feudal lords spent most of
their strength in quarrelling with each other, but de Toesny's
appearance gave the signal for a league against the ruler whom they
despised. William was no longer a child, and rumors of his
premature sagacity, and his uncommon strength and quickness in
war, were flying about from town [Pg197] to town and warned his
enemies that they had no time to lose if they meant to crush him
down. He was a noble-looking lad and had shown a natural
preference for a soldier's life; at fifteen he had demanded to be
made a knight of the old Norman tradition in which lurked a memory
of Scandinavian ceremonies. None save Duke William could bend
Duke William's bow, and while these glowing accounts of him were
written from a later standpoint, and his story might easily be read
backward, as a fulfilment of prophecy, we can be sure, at least, that
his power asserted itself in a marked way, and that he soon gained
importance and mustered a respectable company of followers as the
beginning of a brilliant and almost irresistible court and army. Even
King Henry of France was jealous of his vassal's rising fame and
popularity, and felt obliged to pay William a deference that his years
did not merit. All through the first twelve years men felt that the boy
William's life was in danger, and that, whatever respect Henry paid
him, was likely to be changed to open animosity and disdain the
moment that there was a good excuse. We have a glimpse now and
then of the lonely lad at his sport in the forest about Falaise and
Valognes, where he set apart preserves for hunting. We follow him
from Alan of Brittany's wardship, to the guardian he chose himself,
who held the place of tutor with that of captain-general of the
Norman army, but, guardian or no guardian, he pushed forward
single-handed, and mastered others, beside himself, in a way that
the world never will cease to wonder at. [Pg198]
Roger de Toesny refused allegiance to begin with, and with loud
expressions of his scorn of the Bastard, began to lay waste his
neighbors' lands as if they, too, had been Saracens and merited any
sort of punishment. We first hear the name of De Beaumont, famous
enough ever since, in an account of a battle which some of Roger's
outraged victims waged against him. Grantmesnil, too, is a name
that we shall know very well by and by, when William has gone over
to England with his Norman lords. Normandy never got over its
excitement and apparent astonishment at William's presence and
claims; but even in his boyhood he was the leader of a party. "So
lively and spirited was he, that it seemed to all a marvel," says one
of the old chroniclers, with enthusiasm. When he began to take deep
interest in his affairs, the news of revolts and disorderliness in the
country moved him to violent fits of irritation, but he soon learned to
hide these instinctively, and the chronicle goes on to say that he
"had welling up in his child's heart all the vigor of a man to teach the
Normans to forbear from all acts of irregularity." In this outbreak
against de Toesny he found an irresistible temptation to assert his
mastery, and boy as he was, he really made himself felt; De Toesny
was killed in the fierce little battle, and his death gave a temporary
relief from such uprisings; but William comes more and more to the
front, and all Normandy takes sides either for or against him. This
was no insignificant pretender, but one to be feared; his guardians
and faithful men who had held to him for good or bad reasons, were
mostly put out of the way [Pg199] by their enemies, and there was
nobody at last who could lead the Bastard's men to battle better
than he could himself.
Henry of France had been biding his time, and now Guy of
Burgundy, the son of William's cousin, whom he had welcomed
kindly at his feudal court, puts in a claim to the dukedom of
Normandy. He helped forward a conspiracy, and one night, while
William was living in his favorite castle at Valognes, the jester came
knocking with his bauble, and crying at the chamber door, begging
him to fly for his life: "They are already armed; they are getting
ready; to delay is death!" cried poor Golet the fool; and his master
leaped out of bed, seized his clothes, and ran to the stables for his
horse. Presently he was galloping away toward Falaise for dear life,
and to this day the road he took is called the Duke's road. This was
in 1044, and William was nineteen years old. He was not slow to
understand that the rebels had again risen, and that the conspiracy
was more than a conspiracy; it was a determined insurrection. All
the night long, as he rode across the country in the bright
moonlight, he was thinking about his plans, no doubt, and great
energies and determinations were suddenly waked in his heart. This
was more than a dislike of himself and the tan-yard inheritance; it
was the old rivalry of the Frenchmen and Northmen. The old
question of supremacy and race prejudice was to be fought over
once more and for the last time with any sort of distinctness. This
was not the petty animosity of one baron or another; it was almost
the whole nobility of Normandy against their duke. [Pg200]
There was one episode of the duke's journey which is worth
telling: He had ridden for dear life, and had forded many a stream,
and one, more dangerous, tide inlet where the rivers Oune and Vire
flowed out to sea; and when he got safe across, he went into the
Church of St. Clement, in the Bayeux district, to kneel down and say
his prayers.
As the sun rose, he came close to the church and castle of Rye,
and the Lord of Rye was standing at the castle gate in the clear
morning air. William spurred his horse, and was for hurrying by, but
this faithful vassal, whose name was Hubert, knew him, and stopped
him, and begged to be told the reason of such a headlong journey.
The Lord of Rye was very hospitable, and the tired duke dismounted,
and was made welcome in the house; and presently a fresh horse
was brought out for him, and the three brave sons of the loyal house
were mounted also to ride by his side to Falaise. This hospitality was
not forgotten. Later, in England, their grateful guest set them in high
places, and favored them in princely fashion. Guy, of Burgundy had
been brought up with William as a friend and kinsman, and had
been treated with great generosity. He was master of some great
estates, and one of these was a powerful border fortress between
Normandy and France. His friends were many, and he found
listeners enough to his propositions. Born of the princely houses of
Burgundy and Normandy, he claimed the duchy as his inherited
right; and while so many in court and camp were ashamed of their
lawful leader, and ready to deny his authority, came Guy's
opportunity. [Pg201]
William was cautious, and not without experience. When he was
only a baby he had caught at the straw on which he lay, and would
not let go his hold, and this sign of his future power and persistence
had been proved a true one. The quarrelsome, lawless lords felt that
their days of liberty for themselves, and oppression of everybody
else, would soon be over if they did not strike quickly. They dreaded
so strong and stern a master, and rallied to the standard of the
Bastard's rival, Guy of Burgundy.
There were some of the first nobles of the Côtentin who forsook
their young duke for this rival who was hardly Norman at all, as they
usually decided such points. His Norman descent was on the spindle
side rather than the sword, to use the old distinction, and his
mother's ancestors would not have prevented him in other days from
being called almost a Frenchman. There is a tradition that Guy
promised to divide the lands of Normandy with his allies, keeping
only the old French grant to Rolf for himself, and this must have
been the cause of the treason of the descendants of Rolf's and
William Longsword's loyal colonists. It would amaze us to see the
change in the life and surroundings of the feudal lords even in the
years of William's minority. The leader of the barons in the revolt
was the Viscount of Coutances, the son of that chief who had
defeated Æthelred of England and his host nearly half a century
before. He lived in a castle on the river Oune, near which he
afterward built his great St. Saviour's Abbey. This was the central
point of the insurrection, and from his tower Neal of St. [Pg202]
Saviour could take a wide survey of his beautiful Côtentin country
with its plough-land and pastures and forests, the great minster of
Lessay, and the cliffs and marshes; the sturdy castles of his feudal
lords scattered far and wide. There came to Saint Saviour's also
Randolf of Bayeux, and Hamon of Thorigny and of Creuilly, and
Grimbald of Plessis, and each of them made his fortress ready for a
siege, and swore to defend Guy of Burgundy and to use every art of
war and even treachery to subdue and disgrace William. I say "even
treachery," but that was the first resort of these insurgents rather
than the last. They had laid the deep plot to seize and murder him at
Valognes, and Grimbald was to have struck the blow.
King Henry of France was another enemy at heart. It is difficult
at first to understand his course toward his young neighbor. He
never had fairly acknowledged him, and William on his part had
never put his hands into the king's and announced with the loyal
homage of his ancestors that he was Henry's man. While Normandy
was masterless in William's youth, there was a good chance, never
likely to come again in one man's lifetime, for the king to assert his
authority and to seize at least part of the Norman territory. The
discontent with the base-born heir to the dukedom might not have
been enough by itself to warrant such usurpation, but then, while
the feudal lords were in such turmoil and so taken up with, for the
most part, merely neighborhood quarrels; while they had so little
national and such fierce sectional feeling, would have [Pg203] been the
time for an outsider to enrich himself at their expense. It was not
yet time for Normandy to be provoked into a closer unification by
any outside danger. The French and Scandinavian factions were still
distinct and suspicious of each other, but it was already too late
when King Henry at last, without note or warning, poured his
soldiers across the Norman boundary and invaded the Evreçin; too
late indeed in view of what followed, and in spite of the temporary
blazing up of new jealousies and the revival of old grievances and
hatreds. Henry won a victory and triumph for the time being; he
demanded the famous border castle of Tillières and insisted that it
should be destroyed, and though the brave commander held out for
some time even against William's orders, he finally surrendered.
Henry placed a strong garrison there at once, and after getting an
apparently strong hold on Normandy there followed a time of peace.
The king seemed to be satisfied, but no doubt the young duke's
mind was busy enough with a forced survey of his enemies, already
declared or still masked by hypocrisy, and of his own possible and
probable resources. A readiness to do the things that must be done
was making a true man of Duke William even in his boyhood. For
many years he had seen revolt and violence grow more easy and
more frequent in his dukedom; the noise of quarrels and fighting
grew louder and louder. In his first great battle at Val-ès-dunes the
rule of the Côtentin lords and Guy of Burgundy, or the rule of William
the Bastard, struggled for the mastery. [Pg204]
It was a great battle in importance rather than in numbers.
William called to his loyal provinces for help, and the knights came
riding to court from the romance-side of Normandy, while from the
Bessin and the Côtentin the rebels came down to meet them. It
seems strange that, when William represents to us the ideal
descendant of the Northmen, the Scandinavian element in his
dukedom was the first to oppose him. For once King Henry stood by
his vassal, and when William asked for help in that most critical time,
it was not withheld. Henry had not been ashamed to take part with
the Norman traitors in past times, and now that there was a chance
of breaking the ducal government in pieces and adding a great
district to France, we are more than ever puzzled to know why he
did not make the most of the occasion. Perhaps he felt that the rule
of the dukes was better than the rule of the mutinous barons of the
Côtentin, and likely, on the whole, to prove less dangerous. So when
William claimed protection, it was readily granted, and the king
came to his aid at the head of a body of troops, and helped to win
the victory.
We hear nothing of the Norman archers yet in the chronicler's
story of the fight. They were famous enough afterward, but this
battle was between mounted knights, a true battle of chivalry. The
place was near the river Orne, and the long slopes of the low hills
stretched far and wide, covered with soft turf, like the English downs
across the Channel, lying pleasantly toward the sun. Master Wace
writes the story of the day in the "Roman de Rou," [Pg205] and
sketches the battle-field with vivid touches of his pen. Mr. Freeman
says, in a note beneath his own description, that he went over the
ground with Mr. Green, his fellow-historian, for company, and Master
Wace's book in hand for guide. In the "Roman de Rou" there is a
hint that not only the peasantry, but the poorer gentlemen as well,
were secretly on William's side, that the prejudice and distrust
toward the feudal lords was very great, and that there was more
confidence in a sovereign than in the irksome tyranny of less
powerful lords.
The barons of Saxon Bayeux and Danish Coutances were
matched against the loyal burghers of Falaise, Romanized Rouen,
and the men of the bishop's cities of Liseux and Evreux. King Henry
stopped at the little village of Valmeray to hear mass, as he came up
from the south with his followers, and presently the duke joined
them in the great plain beyond. The rebels are there too; the horses
will not stand in place together, they have caught the spirit of the
encounter, and the bright bosses of the shields; the lances, tied with
gay ribbons, glitter and shine, as the long line of knights bends and
lifts and wavers like some fluttering gay decoration,—some many-
colored huge silken splendor all along the green grass. The birds fly
over swiftly, and return as quickly, puzzled by the strange
appearance of their country-side. Their nests in the grass are
trampled under foot—the world is alive with men in armor, who
laugh loudly and swear roundly, and are there for something
strange, to kill each other if they can, rather than live, for the sake
of [Pg206] Normandy. Far away the green fields stretch into the haze,
the cottages look like toys, and the sheep and cattle feed without
fear in the pastures. Church towers rise gray and straight-walled into
the blue sky. It is a great day for Normandy, and her best knights
and gentlemen finger their sword-hilts, or buckle their saddle-girths,
and wait impatiently for the battle to begin on that day of Val-ès-
dunes.
Among the Côtentin lords was Ralph of Tesson, lord of the forest
of Cinquelais and the castle of Harcourt-Thury. Behind him rode a
hundred and twenty knights, well armed and gallant, who would
follow him to the death. He had sworn on the holy relics of the
saints at Bayeux to smite William wherever he met him, yet he had
no ground for complaint against him. His heart fell when he saw his
rightful lord face to face. A tanner's grandson, indeed, and a man
whose father and mother had done him wrong; all that was true, yet
this young Duke William was good to look upon, and as brave a
gentleman as any son of Rolf's, or the fearless Richard's. Ralph
Tesson (the Badger they called him), a man both shrewd and
powerful, stood apart, and would not rank himself and his men with
either faction, and his knights crowded round him, to remind him
that he had done homage once to William, and would fight against
his natural lord. The Côtentin lords were dismayed and angry, they
promised him great rewards, but nothing touched him, and he stood
silent, a little way from the armies. The young duke and the king
noticed him, and the six-score-and-six brave knights in his troop, all
with their [Pg207] lances raised and trimmed with their ladies' silk
tokens. William said that they would come to his aid; neither Tesson
nor his men had any grudge against him.
Suddenly Tesson put spurs to his horse, and came dashing across
the open field, and all the lords and gentlemen held their breath as
they watched him. "Thury! Thury!" he shouted as he came, and
"Thury! Thury!" the cry echoed back again from the distance. He
rode straight to the duke; there was a murmur from the Côtentin
men; he struck the duke gently with his glove. It was but a playful
mockery of his vow to the saints at Bayeux; he had struck William,
but he and his knights were William's men again; the young duke
said, "Thanks to thee!" and the fight began, all the hotter for the
anger of the deserted barons and their desire for revenge. The day
had begun with a bad omen for their success. "Dexaide!" the old
Norman war-cry, rang out, and those who had followed the lilies of
France cried "Montjoie Saint Denis!" as they fought.
Nowadays, a soldier is a soldier, and men who choose other
professions can keep to them, unless in their country's extremity of
danger, but in that day every man must go to the wars, if there were
need of him, and be surgeon or lawyer, and soldier too; yes, even
the priests and bishops put on their swords and went out to fight. It
would be interesting to know more names on the roll-call that day at
Val-ès-dunes, but we can almost hear the shouts to the patron
saints, and the clash of the armor. King [Pg208] Henry fought like a
brave man, and the storm of the battle raged fiercest round him.
The knights broke their lances, and fought sword to sword. There
was no play of army tactics and manœuvring, but a hand-to-hand
fight, with the sheer strength of horse and man. Once King Henry
was overthrown by the thrust of a Côtentin lance, and sprang up
quickly to show himself to his men. Again he was in the thickest of
the encounter, and was met by one of the three great rebel chiefs
and thrown upon the ground, but this Lord of Thorigny was struck,
in his turn, by a loyal French knight, and presently his lamenting
followers carried him away dead on his shield like any Spartan of
old. And the king honored his valor and commanded that he should
be buried with splendid ceremonies in a church not far from the
battlefield. Long afterward the Norman men and women loved to
sing and to tell stories about the young Duke William's bravery and
noble deeds of arms in that first great fight that made him duke
from one end of Normandy to the other. He slew with his own hand
the noblest and most daring warrior of Bayeux. Master Wace, the
chronicler, tells us how William drove the sharp steel straight
through his hardy foe, and how the body fell beneath his stroke and
its soul departed. Wace was a Bayeux man himself, and though he
was a loyal songster and true to his great duke, he cannot help a
sigh of pride and sorrow over Hardrez' fate.
Neal of St. Saviour fought steadily and cheered his men eagerly
as the hour went on, but Randolf of Bayeux felt his courage begin to
fail him. Hamon [Pg209] was dead. Their great ally, Hardrez, had been
the flower of his own knights, and he was lying dead of a cruel
sword-thrust there in plain sight. He lost sight of Neal, perhaps, for
he was suddenly afraid of betrayal, and grieved that he had ever put
his helmet on. There is a touching bit of description in the "Roman
de Rou" just now. The battle pleased him no more, is told in the
quaint short lines. He thought how sad it was to be a captive, and
sadder still to be slain. He gave way feebly at every charge; he
wandered to and fro aimlessly, a thing to be stumbled over, we fancy
him, now in the front of the fight, now in the rear; at last he
dropped his lance and shield. "He stretched forth his neck and rode
for his life," says Master Wace, quite ashamed of his countryman.
But we can see the poor knight's head drooping low, and his good,
tired horse—the better man of the two—mustering all his broken
strength to carry his master beyond the reach of danger. All the
cowards rode after him pell-mell, but brave Saint Saviour fought to
the last and held the field until his right arm failed and he could not
strike again. The French pressed him hard, the Norman men looked
few and spent, and the mighty lord of the Côtentin knew that all
hope was lost. There on the rising ground of Saint Lawrence the last
blow was struck.
Away went the rebels in groups of three or four—away for dear
life every one of them, riding this way and that, trying to get out of
reach of their enemies and into some sort of shelter. The duke
chased them like a hound on the track of hares on, on [Pg210] toward
Bayeux, past the great Abbey of Fontenay and the Allemagne
quarries, until they reached the river Orne with its deep current. Men
and horses floundered in the water there, and many hot wounds
tinged it with a crimson stain. They were drowned, poor knights,
and poor, brave horses too. They went struggling and drifting down
stream; the banks were strewn with the dead; and the mill-wheels
of Borbillon, a little farther down, were stopped in their slow turning
by the strange wreck and floating worthless fragments of those lords
and gentlemen who had lost the battle of the Val-ès-dunes.
And William was the conqueror of Normandy. Guy of Burgundy
was a traitor to his friends, and won a heritage of shame for his
flight from the field. We hear nothing of him while the fight went on,
only that he ran away. It appears that he must have been one of the
first to start for a place of safety, because they blame him so much;
there is nothing said about all the rebels running away together a
little later. That was the fortune of war and inevitable; not personal
cowardice, they might tell us. Guy of Burgundy was the man who
had led the three Côtentin lords out by fair promises and taunts
about their bastard duke, and he should have been brave and full of
prowess, since he undertook to be the rival of so brave a man. He
did not go toward the banks of the fateful river, but in quite another
direction to his own castle of Brionne, and a troop of his vassals
escaped with him and defended themselves there for a long time,
until William fairly starved them out like rats in a hole. They held
[Pg211] their own bravely, too, and no man was put to death when

they surrendered, while Guy was even allowed to come back to


court. Master Wace stoutly maintains that they should have been
hung, and says long afterward that some of those high in favor at
court were the traitors of the great rebellion.
Strange to say, nobody was put to death. Mr. Freeman says of
this something that gives us such a clear look at William's character
that I must copy it entire. "In those days, both in Normandy and
elsewhere, the legal execution of a state criminal was an event that
seldom happened. Men's lives were recklessly wasted in the endless
warfare of the times, and there were men, as we have seen, who did
not shrink from private murder, even in its basest forms. But the
formal hanging or beheading of a noble prisoner, so common in later
times, was, in the eleventh century, a most unusual sight. And,
strange as it may sound, there was a sense in which William the
Conqueror was not a man of blood. He would sacrifice any number
of lives to his boundless ambition; he did not scruple to condemn his
enemies to cruel personal mutilations; he would keep men for years
as a mere measure of security, in the horrible prison-houses of those
days; but the extinction of human life in cold blood was something
from which he shrank."
At the time of the first great victory, the historian goes on to say,
William was of an age when men are commonly disposed to be
generous, and the worst points of his character had not begun to
show themselves. Later in life, when he had broken the [Pg212] rule, or
perhaps we must call it only his prejudice and superstition, we find
that the star of his glory is already going down, pale and spent, into
the mists of shame and disappointment.
None of the traitors of the Val-ès-dunes were treated harshly,
according to the standard of the times. The barons paid fines and
gave mortgages, and a great many of them were obliged to tear
down their robber castles, which they had built without permission
from the duke. This is the reason that there are so few ruins in
Normandy of the towers of that date. The Master of St. Saviour's
was obliged to take himself off to Brittany, but there was evidently
no confiscation of his great estates, for we find him back again at
court the very next year, high in the duke's favor and holding an
honorable position. He lived forty-four years after this, an
uncommon lifetime for a Norman knight, and followed the Conqueror
to England, but he got no reward in lands and honor, as so many of
his comrades did. Guy of Burgundy stayed at court a little while, and
then went back to his native province and devoted himself to making
plots against his brother, Count William. Grimbald de Plessis fared
the worst of all the conspirators; he was taken to Rouen and put into
prison weighted down with chains, and given the poorest of
lodgings. He confessed that he had tried to murder William that
night at Valognes, when the court jester gave warning, and said that
a knight called Salle had been his confederate. Salle denied the
charge stoutly and challenged De Plessis to fight a judicial combat,
but before the day came the [Pg213] scheming, unlucky baron from the
Saxon lands was found dead in his dungeon. The fetters had ground
their way into his very bones, and he was buried in his chains, for a
warning, while his estates were seized and part of them given to the
church of Bayeux.
Now, at last, the Norman priests and knights knew that they had
a master. For some time it was surprisingly quiet in Normandy, and
the country was unexpectedly prosperous. The great duchy stood in
a higher rank among her sister kingdoms than ever before, and
though there was another revolt and serious attacks from envious
neighbors, yet the Saxons of the Bessin and the Danes of the
Côtentin were overthrown, and Normandy was more unitedly
Norman-French than ever. There had been a long struggle that had
lasted from Richard the Fearless' boyhood until now, but it was
ended at last, to all intents and purposes. Even now there is a
difference between the two parts of Normandy, though so many
years have passed; but the day was not far off after this battle of
Val-ès-dunes when the young conqueror could muster a great army
and cross the channel into England. "The Count of Rouen," says
Freeman, "had overcome Saxons and Danes within his own
dominions, and he was about to weld them into his most trusty
weapons, wherewith to overcome Saxons and Danes beyond the
sea."
Perhaps nothing will show the barbarous cruelty of these times or
William's fierce temper better than the story of Alençon and its
punishment. William Talvas, the young duke's old enemy, formed a
rebellious league with Geoffry of Anjou, and they undertook [Pg214] to
hold Alençon against the Normans. When William came within sight
of the city, he discovered that they had sufficient self-confidence to
mock at him and insult him. They even spread raw skins over the
edge of the city walls, and beat them vigorously, yelling that there
was plenty of work for the tanner, and giving even plainer hints at
what they thought of his mother's ancestry.
William was naturally put into a great rage, and set himself and
his army down before the walls his enemies thought so invincible.
He swore "by the splendor of God" that he would treat them as a
man lops a tree with an axe, and, sure enough, when the siege was
over, and Alençon was at the Conqueror's mercy, he demanded
thirty-two captives of war, and nose, hands, and feet were chopped
off, and presently thrown back over the walls into the town.

[Pg215]
XI.
THE ABBEY OF BEC.
"He heard across the howling seas,
Chime convent bells on wintry nights."
—Matthew Arnold.

The only way of escaping from the obligations of TOC, INDX


feudalism and constant warfare was by forsaking the follies
of the world altogether for the shelter of a convent, and there
devoting one's time and thought to holy things. A monastic life often
came to be only an excuse for devotion to art or to letters, or served
merely to cover the distaste for military pursuits. It was not alone
ecclesiasticism and a love for holy living and thoughts of heaven that
inspired rigid seclusion and monkish scorn of worldliness. Not only
popular superstition or recognition of true spiritual life and growth of
the Church made up the Church's power, but the presence of so
much secular thought and wisdom in the fold. Men of letters, of
science, and philosophy made it often more than a match for the
militant element of society, the soldiery of Normandy, and the great
captains, who could only prove their valor by the strength of their
strategy and their swords. William was quick to recognize the vast
strength of the clergy and the [Pg216] well-protected force of cloistered
public opinion. A soldier and worldly man himself, he arrayed himself
on the side of severe self-repression and knightly chastity and purity
of life, and kept the laws of the convent in high honor; while he
mixed boldly with the rude warfare of his age. He did not think
himself less saintly because he was guilty of secret crimes against
his rivals. A skilful use of what an old writer calls "the powder of
succession" belonged as much to his military glory as any piece of
field-tactics and strategy. He was anxious to stand well in the Pope's
estimation, and the ban and malediction of the Church was
something by all means to be avoided. The story of his marriage
shows his bold, adventurous character and determination in a
marked way, and his persistence in gaining his ends and winning the
approval of his superior, in spite of obstacles that would have
daunted a weaker man. To gain a point to which the Church
objected he must show himself stronger than the Church.

Go to Illus. List

DOORWAY OF CATHEDRAL, CHARTRES.

So there were two great forces at work in Normandy: this


military spirit, the love of excitement, of activity, and adventure; and
this strong religious feeling, which often made the other its willing
servant, and was sometimes by far the most powerful of the two.
Whether superstition or true, devout acceptance and unfolding of
the ideas of the Christian religion moved the Normans and their
contemporaries to most active service of the Church, we will not
stop to discuss. The presence of the best scholars and saints in any
age is a leaven and inspiration of that age, and men cannot help
being more or less [Pg217] influenced by the dwelling among them of
Christ's true disciples and ministers. That there was a large amount
of credulity, of superstitious rites and observances, we cannot doubt,
neither can we question that these exercised an amazing control
over ignorant minds. Standing so near to a pagan ancestry, the
people of large, and, relatively speaking, remote districts of
Normandy, were no doubt confused by lingering vestiges of the older
forms of belief. As yet, religion, in spite of the creeds of [Pg218]
knighthood, showed itself more plainly in stone and mortar, in
vestments, and fasts, and penances, and munificent endowments,
than in simple truth and godliness of life. A Norman nobleman, in
the time of the Conqueror, or earlier, thought that his estate would
lack its chief ornament if he did not plant a company of monks in
some corner of it. It was the proper thing for a rich man to found a
monastery or religious house of some sort or other, and this was a
most blessed thing for the scholars of their time. The profession of
letters was already becoming dignified and respectable, and the
students of the Venerable Bede, and other noble teachers from both
north and south, had already scattered good seeds through the
states of Europe. It was in this time that many great schools were
founded, and in the more peaceful years of the early reign of the
Conqueror, religion and learning found time to strike a deeper root in
Normandy than ever before. There was more wealth for them to be
nourished with, the farms were productive, and the great centres of
industry and manufacture, like Falaise, were thriving famously. It
was almost as respectable to be a monk as to be a soldier. There is
something very beautiful in these earlier brotherhoods—a purer
fashion of thought and of life, a simplicity of devotion to the higher
duties of existence. But we can watch here, as in the later
movements in England and Italy, a gradual change from poverty and
holiness of life, to a love of riches and a satisfaction with corrupt
ceremonies and petty authority. The snare of worldliness finds its
victims always, and the temptation was easy then, [Pg219] as it is easy
now, to forget the things that belong to the spirit. We have seen so
much of the sword and shield in this short history that we turn
gladly away for a little space to understand what influences were
coming from the great abbeys of Bec and Saint Evreuil, and to make
what acquaintance we can with the men who dwelt there, and held
for their weapons only their mass-books and their principles of
education and of holy living. Lanfranc we must surely know, for he
was called the right-hand man of the Conqueror; and now let us go
back a little way and take a quick survey of the founding of the
Abbey of Bec, and trace its history, for that will help us to
understand the monastic life, and the wave of monasticism that left
so plain a mark upon the headlands and valleys of Normandy. Both
in England and Norman France, you can find the same red-roofed
villages clustered about high square church towers, with windows in
the gray stone walls that look like dim fret-work or lace-work. The
oldest houses are low and small, but the oldest minsters and parish
churches are very noble buildings.
The first entrance into one of the old cathedrals is an event in
one's life never to be forgotten. It grows more beautiful the longer
one thinks of it; that first impression of height and space, of silence
and meditation; the walls are stored with echoes of prayers and
chanting voices; the windows are like faded gardens, with their
sober tints and gleams of brighter color. The saints are pictured on
them awkwardly enough, but the glory of heaven beams through the
old glass upon the worn tombstones in [Pg220] the floor; the very dust
in the rays of sunlight that strike across the wide, solemn spaces,
seems sacred dust, and of long continuance. We shut out this busy
world when we go into the cathedral door, and look about us as if
this were a waiting-room from whence one might easily find
conveyance to the next world. There is a feeling of nearness to
heaven as we walk up the great aisle of what our ancestors called,
reverently enough, God's house. One is suddenly reminded of many
unseen things that the world outside gives but little chance to think
about. We are on the journey heavenward indeed. There where
many centuries have worn away the trace of worldliness and the
touch of builders' tools, so that the building itself seems almost to
have grown by its own life and strength, you think about the
builders and planners of such dignity and splendor more than any
thing, after all. Who were the men that dared to lift the roof and
plant the tall pillars, and why did they, in those poor, primitive times,
give all they had to make this one place so rich and high. The bells
ring a lazy, sweet chime for answer, and if you catch a glimpse of
some brown old books in the sacristy, and even spell out the quaint
records, you are hardly satisfied. We can only call them splendid
monuments of the spirit of the time (almost uncivilized, according to
our standard) when nevertheless there was a profound sentiment of
worship and reverence.

Go to Illus. List
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookball.com

You might also like