100% found this document useful (3 votes)
80 views90 pages

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

The document provides information about various textbooks on object-oriented programming, including 'Microsoft Visual C# 2017: An Introduction to Object-Oriented Programming' by Joyce Farrell. It includes links to download these textbooks in multiple formats such as PDF, ePub, and MOBI. The document also lists other related programming books and their details.

Uploaded by

swpjachim
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 (3 votes)
80 views90 pages

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

The document provides information about various textbooks on object-oriented programming, including 'Microsoft Visual C# 2017: An Introduction to Object-Oriented Programming' by Joyce Farrell. It includes links to download these textbooks in multiple formats such as PDF, ePub, and MOBI. The document also lists other related programming books and their details.

Uploaded by

swpjachim
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/ 90

Microsoft Visual C# 2017 An Introduction to

Object Oriented Programming 7th Edition by Joyce


Farrell ISBN 1337102100 9781337102100 download

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

Instantly Access and Download Textbook at https://ebookball.com


Get Your Digital Files Instantly: PDF, ePub, MOBI and More
Quick Digital Downloads: PDF, ePub, MOBI and Other Formats

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
XVIII BUILDING A SKYSCRAPER,
NEW YORK
This was the end, and a most pictorial end, of the old Everett
House, a hotel which had character as so few now have—in New
York. I saw it one cold November night and made the sketch on my
way to a dinner party in old New York. The dinner waited till I got a
sketch done, for I knew the construction man would not. So it was
done.
XIX BUILDING THE WOOLWORTH
BUILDING
Here is a moody colossus—sometimes it is fine, sometimes filthy.
It was all right the day I made this drawing, stately amid the clouds.
One thing it has done—it has made a new sky line and brought New
York together again. It comes up best from the river, but no longer
do the Brooklyn river-boats run; from them I used to get the best
views. Still, there are other ways of seeing the Wonder of Work even
now at New York.
XX BUTTE, MONTANA, ON ITS
MOUNTAIN TOP
Butte is the most pictorial place in America—therefore no one
stops at it—and most people pass it in the night, or do not take the
trouble to look out of the car windows as they go by. But there it is.
On the mountain side spring up the huge shafts. The top is crowned
not with trees but with chimneys. Low black villages of miners'
houses straggle toward the foot of the mountain. The barren plain is
covered with gray, slimy masses of refuse which crawl down to it—
glaciers of work—from the hills. The plain is seared and scored and
cracked with tiny canyons, all their lines leading to the mountain. If
you have the luck to reach the town early in the morning you will
find it half revealed, half concealed in smoke and mist and steam,
through which the strange shafts struggle up to the light, while all
round the horizon the snow peaks silently shimmer above the noisy,
hidden town. If you have the still better fortune to reach it late in
the evening you will see an Alpine glow that the Alps have never
seen. In the middle of the day the mountains disappear and there is
nothing but glare and glitter, union men and loafers about.
XXI ANACONDA, MONTANA
I have seen many volcanoes, a few in eruption—that was terrible
—but this great smelter at Anaconda always, while I was there,
pouring from its great stack high on the mountain its endless cloud
pall of heavy, drifting, falling smoke, was more wonderful—for this
volcano is man's work and one of the Wonders of Work. Dead and
gray and bare are the nearby hills, glorious the snow-covered peaks
far off, but incredible is this endless rolling, changing pillar of cloud,
always there, yet always different—and that country covered with
great lakes, waterless, glittering, great lava beds of refuse stretching
away in every direction down the mountain sides into the valleys,
swallowing up every vestige of life, yet beautiful with the beauty of
death—a death, a plague which day by day spreads farther and
farther over the land—silently overwhelming, all-devouring—a silent
place of smoke and fire.
XXII APPROACH TO DULUTH, THE
LAND OF WORK AND BEAUTY
The lines of the winding waterways, each leading to a furnace, a
mill, an elevator, are simply beautiful and the color absolutely lovely.
This is the modern landscape—a landscape that Claude would have
loved. All his composition is in it—only the mills have replaced the
palaces, the trestle the aqueduct; instead of the stone pine, there
stands the water tower; instead of the cypress, the automatic signal;
instead of the Cross, the trolley pole. Soon, however, all this will go
—the mystery of the smoke will vanish in the clearness of electricity,
and the mystery of the trestle in the plainness of the concrete
bridge. But it is here now, and the thing is to delight in it. Artists
don't see it—and the railroad men who have made it don't know any
more than the Greeks what a marvellous thing they have made.
XXIII ORE WHARVES, DULUTH
Mighty, terrifying are these monsters—filled chock-full with ore,
which, when the empty steamers come alongside, vomit roaring red
and gold and brown streams of ore that load them in half an hour, or
less, and then are ready for more.
XXIV ORE MINES, HIBBING
If one wants an idea of what the Culebra Cut looked like, when
the Panama Canal was being dug through the mountains, it is only
necessary to go to the ore mines near Duluth. There are the same
great terraces, the same steam shovels, digging and loading the dirt,
the same engines and trains, and in some of the pits the forms are
even fine—amphitheatres,—only the seats and steps are gigantic.
But when the shadows begin to creep up from below, the place
becomes a theatre for the gods, a theatre where there are no
spectators, and the actors are the steam shovels with their white
plumes and the engines with their black clouds. But they are finer
far than any poor mummer's makeshifts. And every now and then
comes a burst of applause as a blast is fired more thrilling than ever
heard in a play theatre. This is the theatre of the Wonder of Work.
XXV FLOUR MILLS, MINNEAPOLIS
The mills of Minneapolis are as impressive as the cathedrals of
France. There are places on the river where they group themselves
into the same compositions, with the bridges below them, that I
found years ago at Albi—only the color is different: the rosy red of
the French brick is changed to dull concrete gray. The tree masses
below are the same, and the old stone railroad bridge over the
Mississippi is just as drawable as that over the Tarn. The beauty of
the flour mills is the beauty of use—they carry out William Morris's
theory that "everything useful should be beautiful"—but I don't know
what he would have said to them. There are other subjects which
recall Tivoli, where the streams gush out from the bluffs or tumble
and rush and roar from dark caverns between the huge modern
masses of masonry as finely as they do in far-away Italy. Those were
the shrines of the gods—these are the temples of work, the temples
of our time.
XXVI THE INCLINE, CINCINNATI
There are hundreds of these inclines—ascenseurs, finiculari, in
the world—all fascinating from above or below—but I know of none
so fascinating as this even among the numbers at Cincinnati—none
in which the pitch is steeper, the stop so sudden—none where the
streets lead direct to the heart of the city; no city so dominated,
concentrated, at its heart, by its lone white skyscraper, as Cincinnati.
That is why I drew it; and, as I drew, the boy who opened and shut
the gates came and told me he wanted to be a poet, that he was a
poet, and that Poe was the greatest American author, which most
great Americans do not know, and that he loved Shelley, and so I
recommended Whitman to him, of whom he had not heard, and
advised him to attend to his gates and his poetry and then he might
do something. And he asked me if I had done anything myself. If I
had made good! Well, have I?
XXVII VICTOR EMMANUEL
MONUMENT, ROME
A triumph of misdirected work which has swallowed millions with
no result—only while it was being built, the scaffolding which
surrounded it was magnificent, and from where I made the drawing
on the Palatine it told the story of ancient, mediæval, and modern
work in Rome.
XXVIII REBUILDING THE
CAMPANILE, VENICE
The changes in the methods of work between Canaletto's time
and mine were never more clearly shown. When he drew the
building being restored, it was hidden in scaffolding; when it was
rebuilt, as I saw it, a few years ago, everything was done from the
inside, till the top was reached, men and materials being carried up
on elevators. It is said one of our ingenious American Captains of
Labor offered to rebuild it free if the Venetians would let him put two
elevators in, and have the profits of them for twenty-five years, after
which he would hand it to the city and retire on the results. The
Syndic declined, but put in the elevators.
XXIX RETURN FROM WORK,
CARRARA, ITALY
I have never seen anything so impressive as the quarries at
Carrara. The great white masses one can see as the train passes
Carrara station, or from Pisa, are not snow, as many think, but
marble—high on the tops of the mountains, quarried for centuries by
regiments of men who toil on foot, in trains or are swung up in
baskets to the summit. Then down the roughest track, only
smoothed by the blocks, the marble is dragged by teams of oxen,
driven by men sitting backward, to the railroad or the harbor. The
contrast between the dazzling blocks, the blue sky and black trees,
and untouched mountain side is intense.
XXX THE NEW BAY OF BAIE, ITALY
I have no doubt I shall be told I am cheekily reckless to tackle
Turner's subject—I have even known a collector to get rid of this
print with scorn—but I am glad I drew it. I do not know if Turner
made his drawing from the same point. Just where, after the long
climb up the hill from Naples, between the cliffs, the road begins to
descend, it turns, and all this is before you. I do not know whether it
will be in existence when the book appears, or battered to ruin, but I
do know that nowhere in the world is there such a combination of
classic and mediæval motives and the spirit of modern work as in
this view from the top of the hill looking down on the land and the
sea near Naples.
XXXI THE HARBOR AT GENOA,
ITALY
In Italy alone can the wonder of the old and new work be found.
This subject must have been sketched by Claude—for these two
lighthouses appear—or others like them—possibly at Civita Vecchia,
again and again in his paintings. But he never saw the harbor
crowded with steamers, the twinkling lines of electric light, the
cranes, the engines and the docks. I have, and have tried to draw
them all.
XXXII THE GREAT WHITE CLOUD,
LEEDS
I saw this extraordinary effect one day at Leeds. Nothing could
be finer than the way the great, strange furnaces told like castles—
and they are work castles—against the great white clouds of a
summer day in England.
XXXIII POTLAND, ENGLAND
On its little hill, entirely covering it among the Five Towns,
stands this work town. Pottery kilns and chimneys, and not church
spires and campanile, crown it. But in that land of work—coal mines
and factory stacks about—it is perfect as a composition—as fine as
any of the little towns Rembrandt drew and Dürer built. I don't even
know its name.
XXXIV THE RIVER OF WORK,
LEEDS, ENGLAND
Slow-moving, filthy, black—here and there gleams of iridescence
lovely as old glass—that come from oil waste on the water—it winds
smellily through the Black County of England. There are many of
these rivers in the world. Over them brood black, murky clouds,
great black chimneys vomit black smoke, and then for a moment the
sun breaks through and turns all to glory.
XXXV THE GREAT CHIMNEY,
BRADFORD
There it stood, solitary—beyond, behind, below—climbing up the
endless hills silhouetting the horizon, revealed and hidden by
showers, smoke, clouds, chimneys and chimneys and chimneys—the
endless landmarks of industrial England.

This etching illustrates, too, the necessity of doing the Wonder


of Work when you find a subject, and not saying, "I will come again
and do it later"—and you must find your subjects for yourself: no
one can tell you where there is a fine smoke effect or a stunning
steam jet. I had made the etching and later was in Bradford again
and went back to look at it. Not only had it all been fenced in, but a
new factory was being built round it—it had completely disappeared.
Welcome to Our Bookstore - The Ultimate Destination for Book Lovers
Are you passionate about books and eager to explore new worlds of
knowledge? At our website, we offer a vast collection of books that
cater to every interest and age group. From classic literature to
specialized publications, self-help books, and children’s stories, we
have it all! Each book is a gateway to new adventures, helping you
expand your knowledge and nourish your soul
Experience Convenient and Enjoyable Book Shopping Our website is more
than just an online bookstore—it’s a bridge connecting readers to the
timeless values of culture and wisdom. With a sleek and user-friendly
interface and a smart search system, you can find your favorite books
quickly and easily. Enjoy special promotions, fast home delivery, and
a seamless shopping experience that saves you time and enhances your
love for reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!

ebookball.com

You might also like