Microsoft Visual C# 2017 An Introduction To Object Oriented Programming 7th Edition by Joyce Farrell ISBN 1337102100 9781337102100pdf Download
Microsoft Visual C# 2017 An Introduction To Object Oriented Programming 7th Edition by Joyce Farrell ISBN 1337102100 9781337102100pdf Download
https://ebookball.com/product/microsoft-visual-c-2017-an-
introduction-to-object-oriented-programming-7th-edition-by-joyce-
farrell-isbn-1337102100-9781337102100-25038/
https://ebookball.com/product/beginning-c-3-0-an-introduction-to-
object-oriented-programming-1st-edition-by-jack-
purdum-0470261293-978-0470261293-15238/
https://ebookball.com/product/object-oriented-programming-using-
c-an-introduction-1st-edition-by-pardoe-
king-0333692411-978-0333692417-15282/
https://ebookball.com/product/an-introduction-to-object-oriented-
programming-with-java-5th-edition-by-thomas-
wu-0073523305-9780073523309-17244/
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/
https://ebookball.com/product/an-introduction-to-object-oriented-
programming-with-java-5th-edition-by-thomas-wu-
isbn-9780073523309-0073523305-15552/
https://ebookball.com/product/an-introduction-to-object-oriented-
programming-with-java-5th-edition-by-thomas-wu-
isbn-0073523305-9780073523309-16398/
https://ebookball.com/product/c-programming-an-object-oriented-
approach-1st-edition-by-behrouz-forouzan-richard-
gilberg-0073523380-9780073523385-15328/
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
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
J o y c e Fa r r e l l
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]
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
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
C o ntents Contents
Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-202
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
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
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.
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
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
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
CHAPTER 1
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
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
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
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
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/.
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
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#
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#
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#
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.
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
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.
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.
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
class FirstClass
{
static void Main()
{
System.Console.WriteLine("This is my first C# program");
}
}
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");
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#
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.
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
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
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
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
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
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()
{
/*********/;
}
}
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#
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
class ThreeLinesOutput
{
static void Main()
{
System.Console.WriteLine("Line one");
System.Console.WriteLine("Line two");
System.Console.WriteLine("Line three");
}
}
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.
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
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.
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.
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
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.
ebookball.com