Licensed to: iChapters User
Licensed to: iChapters User
Microsoft® Visual C#® 2008
Comprehensive: An Introduction
to Object-Oriented Programming
Joyce Farrell
Executive Editor: Marie Lee
Acquisitions Editor: Amy Jollymore
Managing Editor: Tricia Coia
© 2010 Course Technology, Cengage Learning
ALL RIGHTS RESERVED. No part of this work covered by the copyright herein
may be reproduced, transmitted, stored or used in any form or by any means—
graphic, electronic, or mechanical, including but not limited to photocopying,
recording, scanning, digitizing, taping, Web distribution, information networks,
or information storage and retrieval systems, except as permitted under
Section 107 or 108 of the 1976 United States Copyright Act—without the prior
written permission of the publisher.
Developmental Editor: Dan Seiter
Editorial Assistant: Julia Leroux-Lindsey
Marketing Manager: Bryant Chrzan
Content Project Manager: Heather Furrow
Art Director: Marissa Falco
Cover Designer: Bruce Bond
Cover Photo: © iStockphoto.com/4x6
Manufacturing Coordinator: Julio Esperas
Proofreader: Andrea Schein
Indexer: Alexandra Nickerson
Compositor: International Typesetting
and Composition
For product information and technology assistance, contact us at
Cengage Learning Customer & Sales Support, 1-800-354-9706
For permission to use material from this text or product,
submit all requests online at www.cengage.com/permissions
Further permissions questions can be e-mailed to
permissionrequest@cengage.com
Microsoft® is a registered trademark of the Microsoft Corporation.
ISBN-13: 978-0-495-80643-1
ISBN-10: 0-495-80643-9
Course Technology
25 Thomson Place
Boston, MA 02210
USA
Cengage Learning is a leading provider of customized learning solutions with
office locations around the globe, including Singapore, the United Kingdom,
Australia, Mexico, Brazil, and Japan. Locate your local office at:
international.cengage.com/region
Cengage Learning products are represented in Canada by Nelson Education, Ltd.
For your lifelong learning solutions, visit www.course.cengage.com
Visit our corporate Web site at www.cengage.com
Some of the product names and company names used in this book have been
used for identification purposes only and may be trademarks or registered
trademarks of their respective manufacturers and sellers.
Course Technology, a part of Cengage Learning, reserves the right to revise this
publication and make changes from time to time in its content without notice.
Printed in Canada
1 2 3 4 5 6 7 12 11 10 09
Copyright 2009 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
C H A P T E R O N E
1
A FIRST PROGRAM
USING C#
»
In this chapter you will:
Learn about programming
Explore object-oriented programming concepts
Learn about the C# programming language
Write a C# program that produces output
Learn how to select identifiers to use within your
programs
Add comments to a C# program
Eliminate the reference to Out by using the System
namespace
Write and compile a C# program using the command
prompt and using Visual Studio
Learn alternate ways to write the Main() method
1
Copyright 2009 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
A FIRST PROGRAM USING C#
Programming a computer is an interesting, challenging, fun, and sometimes frustrating task.
It requires you to be precise and careful as well as creative. If you do this, you will find that
learning a new programming language expands your horizons.
As new programming languages are developed and introduced, your job becomes easier and
more difficult at the same time. Programming becomes easier because built-in capabilities are
added to every new language that is developed, and tasks that might have taken you weeks or
months to develop 20 years ago are now included in the language so you can add them to a
program with a few keystrokes. Programming becomes more difficult for the same reason—
new languages have so many features that you must devote a significant amount of time to
learning them.
C# (pronounced “C Sharp”) is a relatively new language that provides you with a wide 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.
PROGRAMMING
A computer program is a set of instructions that you write to tell a computer what to do.
Internally, computers are 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 evolved into an easier task because of the development of
high-level programming languages. 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. High-level languages also allow you to assign
reasonable names to areas of computer memory; you can use names such as “hoursWorked”
or “payRate,” rather than having to remember the memory locations (switch numbers) of
those values.
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
2
Copyright 2009 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
C H A P T E R O N E
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
really are learning the vocabulary and syntax rules for that language.
»
NOTE In some languages, such as BASIC, the language translator is called an interpreter. In others, such as
assembly language, it is called an assembler. These translators operate in different fashions, 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 execute a logically constructed, workable program. 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.
To achieve a working program that accomplishes the tasks it is meant to accomplish, you
must remove all syntax and logical errors from the program. This process is called debugging
the program.
»NOTE
Programmers call
some logical errors
semantic errors.
For example, if you
misspell a programming language word, you
commit a syntax
error, but if you use
a correct word in
the wrong context,
you commit a
semantic error.
»
NOTE 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.
»TWO TRUTHS AND A LIE: PROGRAMMING
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, or rules of the language.
3. Programmers use a computer program called a compiler to translate machine code into a high-level language they
can understand.
The false statement is #3. Programmers use a computer program called a compiler to translate their high-level language
statements into machine code.
3
Copyright 2009 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
A FIRST PROGRAM USING C#
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 of 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. The named computer memory locations
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, a company’s payroll program might contain a variable named payRate. The
memory location referenced by the name payRate might contain different values at different
times. For instance, an organization’s payroll program might contain a different value for
payRate for each of 100 employees. Additionally, a single employee’s payRate variable
might contain different values before or after a raise or before or after surpassing 40 work
hours in one week. During the execution of the payroll program, each value stored under the
name payRate might have many operations performed on it—for example, reading it from an
input device, multiplying it by another variable representing hours worked, and printing it on
paper.
»NOTE
When programmers do not capitalize the first letter of an identifier but do capitalize each new word, as in
payRate, they call the style camel casing, because the identifier appears to have a hump in the middle. When programmers adopt the style of capitalizing the first letter of all new words in an identifier, even the first one, as in PayRate, they
call the style Pascal casing. Most C# programmers use camel casing when creating variable names, but this convention is
not required to produce a workable program.
»NOTE
Depending on the
programming
language, methods
are sometimes
called procedures,
subroutines, or
functions. In C#, the
preferred term is
methods.
For convenience, the individual operations used in a computer program often are grouped
into logical units called procedures or methods. For example, a series of four or five
comparisons and calculations that together determine an employee’s federal tax withholding
value might be grouped as a method named CalculateFederalWithholding(). A procedural
program defines the variable memory locations, then calls or invokes a series of procedures
to input, manipulate, and output the values stored in those locations. A single procedural
program often contains hundreds of variables and thousands of procedure calls.
»
NOTE In C#, methods conventionally are named using Pascal casing, and all method names are followed by a set
of parentheses. When you pronounce a method name, you ignore the parentheses. When this book refers to a method, the
name will be followed with parentheses. This practice helps distinguish method names from variable and class names.
Object-oriented programming is an extension of procedural programming. Object-oriented
programs contain variables, methods, and six other features:
» Objects
» Classes
» Encapsulation
4
Copyright 2009 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
C H A P T E R O N E
» Interfaces
» Polymorphism
» Inheritance
»
NOTE Although procedural and object-oriented programming techniques are somewhat similar, they raise different
concerns in the design and development phase that occurs before programs are written.
The components called objects are similar to concrete objects in the real world. You create
objects that contain their own variables and methods, and then you manipulate those objects
to achieve a desired result. Writing object-oriented programs involves both creating objects
and creating applications that use those objects.
If you’ve ever used a computer that has a command-line operating system (such as DOS), and
if you’ve used a GUI (a graphical user interface, such as Microsoft Windows), then you
already have an idea of the difference between procedural and object-oriented programs. If
you want to move several files from a CD to a hard disk, you can accomplish the task using
either a typed command at a prompt or command line (as in DOS), or using a mouse in a
graphical environment (as in Windows). The difference lies in whether you issue a series of
sequential commands to move the files (in DOS) or drag icons representing the files from
one screen location to another (in Windows). You can move the files using either operating
system, but the GUI system allows you to simulate the way you would move their real-world
paper counterparts. In other words, the GUI system allows you to treat files as objects.
»
NOTE 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 >.
Objects in both the real world and in object-oriented programming are made up of attributes
and methods. The attributes of an object represent its characteristics. For example, some of
your Automobile’s attributes are its make, model, year, and purchase price. Other attributes
describe whether the Automobile is currently running, its gear, its speed, and whether it is
dirty. All Automobiles possess the same attributes, but not the same values, or states, for
those attributes. For example, some Automobiles currently are running, but some are not.
The value of an attribute can change over time; for example, some Automobiles are running
now, but will not be running in the future. Therefore, the states of an Automobile are variable.
Similarly, your Dog has attributes that include its breed, name, age, and shot status (that is,
whether its shots are current); the states for a particular dog might be “Labrador retriever”,
“Murphy”, “7”, and “yes”.
»NOTE
Programmers also
call the values of
an object’s attributes the properties
of the object. The
state of an object is
the collective value
of all its attributes
at any point in time.
A class is a category of objects or a type of object. A class describes the attributes and methods
of every object that is an instance, or example, of that class. For example, Automobile is a
class whose objects have a year, make, model, color, and current running status. Your 2005 red
Chevrolet is an instance of the class that is made up of all Automobiles; so is my supervisor’s
2009 black Porsche. Your Collie named Bosco is an instance of the class that is made up
5
Copyright 2009 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
A FIRST PROGRAM USING C#
of all Dogs; so is my Labrador named Murphy. Thinking of items as instances of a class allows
you to apply your general knowledge of the class to its individual members. The particular
instances of these objects contain all of the attributes that their general category contains;
only the states of those attributes vary. 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 speed or exact contents 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.
»
NOTE By convention, programmers using C# begin their class names with an uppercase letter. 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. However, following this convention is not required to produce a workable program.
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 ascertaining the status of certain attributes, such as the current speed of an Automobile
and the status of its gas 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 can also 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 are then
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 of 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 figure 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, polymorphism, describes the ability
to create methods that act appropriately depending on the context. For example, you are
able to “fill” both a Dog and an Automobile, but you do so by very different means. A friend
would have no trouble understanding your meaning if you said “I need to fill my Automobile”
6
Copyright 2009 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
C H A P T E R O N E
and distinguishing that process from the process of “filling” your Dog, your BankAccount, or
your AppointmentCalendar. Older, non-object-oriented languages could not make such
distinctions, but object-oriented languages can.
Object-oriented languages also support inheritance. 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 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. Using polymorphism, you might need to specialize the Dog’s methods to
be appropriate for a ShowDog. For example, the fill method might be different (perhaps using
more expensive food). 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.
»TWO TRUTHS AND A LIE: OBJECT-ORIENTED PROGRAMMING
1. Procedural programs use variables and tasks that are grouped into methods or procedures.
2. Object-oriented programming languages do not support variables or methods, but they do contain objects and classes.
3. In object-oriented programming, a class is a category of objects or a type of object, and each object is an instance of
a class.
The false answer is #2. Object-oriented programs contain variables and methods just as procedural programs do.
THE C# PROGRAMMING LANGUAGE
The C# programming language was developed as an object-oriented and componentoriented language. It is part of Microsoft Visual Studio 2008, a package designed for developing
applications that run on Windows computers. Unlike other programming languages, C# allows
every piece of data to be treated as an object and to employ the principles of object-oriented
programming. C# provides constructs for creating components with properties, methods, and
events, making it an ideal language for twenty-first-century programming, where building small,
reusable components is more important than building huge, stand-alone applications.
C# contains a GUI interface that makes it similar to Visual Basic. C# is considered more concise
than Visual Basic, and is modeled after the C++ programming language, but some of the most
difficult features to understand in C++ have been eliminated in C#. For example, pointers
are not used in C#, 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#.
»NOTE
Technically, you
can use pointers in
C#, but only in a
mode called
unsafe, which is
rarely used.
C# is very similar to Java, because Java was also based on C++. In Java, simple data types are
not objects; therefore, they do not work with built-in methods. In C#, every piece of data is an
object, providing all data with the functionality of true objects. Additionally, in Java, simple
7
Copyright 2009 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
A FIRST PROGRAM USING C#
parameters (also called primitive parameters) must be passed by value, which means a copy
must be made of any data that is sent to a method for alteration, and the copy must be sent
back to the original object. C# provides the convenience of passing primitive parameters by
reference, which means the actual object can be altered by a method without a copy being
passed back. If you have not programmed before, the difference between C# and other
languages means little to you. However, experienced programmers will appreciate the
thought that the developers of C# put into its features.
»NOTE
Microsoft
Corporation refers
to the current version of C# as C# 3.5.
You can find
Microsoft’s C#
specifications at
msdn.microsoft.
com/vcsharp/
programming/
language.
»NOTE
Primitive data is simple data, such as a number, as opposed to complex data, such as an Employee, a
BankAccount, or an Automobile. In Chapter 2, you will learn about C#’s simple data types—those that are intrinsic to
the language. In Chapter 7, you will create complex objects that are composed of primitive data types.
»
NOTE 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 /publication /standards/Ecma-334.htm.
»TWO TRUTHS AND 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.
The false statement is #3. C# is modeled after the C++ programming language, but some of the most difficult features to
understand in C++ have been eliminated in C#.
WRITING A C# PROGRAM
THAT PRODUCES OUTPUT
»NOTE
Some words
appear in blue in
Figure 1-1. These
are C# keywords. A
complete list of
keywords appears
in Table 1-1.
At first glance, even the simplest C# program involves a fair amount of confusing syntax.
Consider the simple program in Figure 1-1. This program is written on seven lines, and its
only task is to display “This is my first C# program” on the screen.
public class FirstClass
{
public static void Main()
{
System.Console.Out.WriteLine("This is my first C# program");
}
}
Figure 1-1 FirstClass console application
8
Copyright 2009 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
C H A P T E R O N E
The statement that does the actual work in this program is in the middle of the figure:
System.Console.Out.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.”
»
NOTE The words argument and parameter are closely related. An argument is the expression used when you call
or invoke a method, while a parameter is an object or reference that is declared in a method definition, where the method
instructions are written. You will learn more about the terms call and invoke in Chapter 6. Do not worry if you do not understand arguments and parameters at this point; their uses will become clearer when you write methods in Chapter 6.
»
NOTE Although a string can be an argument to a method, not all arguments are strings. In this book, you will see
and write methods that accept many other types of data.
Within the statement System.Console.Out.WriteLine("This is my first C#
program");, the method to which you are passing the argument string “This is my first C#
program” is named WriteLine(). The WriteLine() method displays output on the
screen and positions the cursor on the next line, where additional output might be displayed
subsequently.
»NOTE
In C#, you usually refer to method names by including their parentheses, as in WriteLine(). This practice
makes it easy for you to distinguish method names from variable names.
»NOTE
The Write() method is very similar to the WriteLine() method. With WriteLine(), the cursor is
moved 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.
9
Copyright 2009 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
A FIRST PROGRAM USING C#
»NOTE
The C# programming language is
case sensitive.
Thus, the object
named Out is a
completely different object than one
named out, OUT,
or oUt.
Within the statement System.Console.Out.WriteLine("This is my first C#
program");, Out is an object. The Out object represents the screen on the terminal or
computer where you are working. Of course, not all objects have a WriteLine() method (for
instance, you can’t write a line to a computer’s mouse, your Automobile, or your 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 Out object was created and endowed with the method
named WriteLine(). Soon, you will create your own C# objects and endow them with your
own methods.
Within the statement System.Console.Out.WriteLine("This is my first C#
program");, Console is a class. It defines the attributes of a collection of similar “Console”
objects, just as the Dog class defines the attributes of a collection of similar Dog objects. One
of the Console objects is Out. (You might guess that another Console object is In, which
represents the keyboard.)
»NOTE
You will create your
own namespaces
in Chapter 3.
Within the statement System.Console.Out.WriteLine("This is my first C#
program");, System is a namespace. A namespace is a scheme or mechanism that provides
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.
»
NOTE 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 statement System.Console.Out.WriteLine("This is my
first C# program"); are used to separate the names of the namespace, class, object,
and method. You will use this same namespace-dot-class-dot-object-dot-method format
repeatedly in your C# programs.
In the FirstClass class in Figure 1-1, the statement System.Console.Out.WriteLine
("This is my first C# program"); appears within a method named Main(). 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. The method body
of every method is contained within a pair of curly braces ({ }) and includes all the instructions
executed by the method. The program in Figure 1-1 includes only one statement between the
curly braces of the Main() method. Soon, you will write methods with many more statements.
In Figure 1-1, the statement within the Main() method (the WriteLine() statement) 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.
For every opening curly brace ({) 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. For example, the method in Figure 1-2 executes exactly the same way as the
one shown in Figure 1-1. The only difference is in the amount of whitespace used in the
method. In general, whitespace is optional in C#. Whitespace is any combination of spaces,
10
Copyright 2009 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
C H A P T E R O N E
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. Usually, vertically aligning each
pair of opening and closing curly braces and indenting the contents between them, as in
Figure 1-1, makes your code easier to read than the format shown in Figure 1-2.
public static void Main(){System.Console.Out.WriteLine
("This is my first C# program");}
Figure 1-2 A Main() method with little whitespace
The method header for the Main() method contains four words. Three of these words are
keywords—predefined and reserved identifiers that have special meaning to the compiler. In
the method header public static void Main(), the word public is an access modifier.
When used in a method header, an access modifier defines the circumstances under which
the method can be accessed. As opposed to cases in which a method is private, the access
modifier public indicates that other classes may use this method.
»NOTE
If you do not use an access modifier within a method header, then by default the method is private. Other
classes cannot use a private method. You will learn more about public and private access modifiers in Chapter 7.
In the English language, the word static means “showing little change” or “stationary.” In C#,
the reserved keyword static has a related meaning. It 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.
In C#, you will create many nonstatic methods within classes that are executed by objects.
For example, you might create a display() method in an Automobile class that you use to
display an Automobile’s attributes. If you create 100 Automobile objects, the display()
method will operate differently and appropriately for each object, displaying different
makes, models, and colors of Automobiles. (Programmers would say a nonstatic method
is “invoked” by each instance of the object.) However, a static method does not require
an object to be used to invoke it. Only one version of the static Main() method for
FirstClass will ever be executed. Of course, other classes eventually might have their
own, different Main() methods. You will learn the mechanics of how static and nonstatic
methods differ in Chapter 4.
In English, the word void means empty. When the keyword void is used in the Main()
method header, it does not indicate that the Main() method is empty, but rather that the method
does not return any value when called. This doesn’t mean that Main() doesn’t produce
output—it does. Instead, it means the Main() method does not send any value back to any
method that calls it. You will learn more about return values when you study methods in
greater detail in Chapter 3.
11
Copyright 2009 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
A FIRST PROGRAM USING C#
In the method header, the name of the method is Main(). All C# applications must include a
method named Main(), and most C# applications will have additional methods with other
names. When you execute a C# application, the Main() method always executes first.
»NOTE
You will write many C# classes that do not contain a Main() method. However, all executable applications
(runnable programs) must contain a Main() method.
»NOTE
You also can write the Main() method header as public static int Main(), public static
void Main(string[] args), or public static int Main(string[] args). You will learn more about these
alternative forms of Main() at the end of this chapter.
TWO TRUTHS AND 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.
The false statement is #1. Strings are literal values represented between quotation marks. Arguments represent information that a method needs to perform its task. Although an argument might be a string, not all arguments are strings.
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 public class FirstClass, you are defining
a class named FirstClass. A class name does not have to contain the word “Class” as
FirstClass does. You can define a C# class using any identifier you need, as long as it meets
the following requirements:
»NOTE
In this book, all
identifiers begin
with a letter.
»NOTE
An identifier with
an @ prefix is a
verbatim identifier.
» 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.)
An identifier can contain only letters or digits, not special characters such as #, $, or &.
An identifier cannot be a C# reserved keyword, such as public or class. 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 “at” sign, as in @class. 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.)
12
Copyright 2009 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
C H A P T E R O N E
abstract
float
return
as
for
sbyte
base
foreach
sealed
bool
goto
short
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
»
NOTE 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.
A programming standard in C# is to begin class names with an uppercase letter and use other
uppercase letters as needed to improve readability. Table 1-2 lists some valid and conventional
class names you might use when creating classes in C#. Table 1-3 lists some class names that
are valid, but unconventional; Table 1-4 lists some illegal class names.
13
Copyright 2009 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
A FIRST PROGRAM USING C#
»NOTE
You should follow
established conventions for C# so
that other programmers can interpret
and follow your
programs. This
book uses established C# programming conventions.
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
Budget2010
Begins with an uppercase letter and contains no spaces
Table 1-2 Some valid and conventional class names in C#
Class Name
Description
employee
Begins with a lowercase letter
First_Class
Although legal, the underscore is not commonly used to indicate new words
Pushbuttoncontrol
No uppercase characters are used to indicate the start of a
new word, making the name difficult to read
BUDGET2010
Appears with all uppercase letters
Public
Although this identifier is legal because it is different from the
keyword public, which begins with a lowercase “p,” 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
2011Budget
Class names cannot begin with a digit
phone#
The # symbol is not allowed; identifiers consist of letters
and digits
Table 1-4 Some illegal class names in C#
14
Copyright 2009 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
C H A P T E R O N E
In Figure 1-1, the line public class FirstClass contains the keyword class, which
identifies FirstClass as a class. The reserved word public is an access modifier. Similar
to the way an access modifier describes a method’s accessibility, when used with a class, the
access modifier defines the circumstances under which the class can be accessed; public
access is the most liberal type of access.
The simple program shown in Figure 1-1 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 that you want to execute.
public class AnyLegalClassName
{
public static void Main()
{
/*********/;
}
}
Figure 1-3 Shell program
»TWO TRUTHS AND 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 or digits, not special characters such as #, $, or &.
3. An identifier cannot be a C# reserved keyword.
The false statement is #1. In C#, an identifier must begin with an underscore, the at sign (@), or a letter. There is no requirement that the initial letter be capitalized, although in C#, it is a convention that the initial letter of a class name is capitalized.
ADDING COMMENTS TO A PROGRAM
As you can see, even the simplest C# program takes several lines of code and contains
somewhat perplexing syntax. Large programs that perform many tasks include much more
code. 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 in the future.
»
NOTE 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.
15
Copyright 2009 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
A FIRST PROGRAM USING C#
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 that
the compiler will ignore it. This approach helps you pinpoint the location of errant statements
in malfunctioning programs.
There are three types of comments in C#:
» 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 at the end 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 from within
a program. These comments, called 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#.
»
NOTE The forward slash (/) and the backslash (\) characters often are confused, but they are distinct characters.
You cannot use them interchangeably.
Figure 1-4 shows how comments can be used in code. The program covers 12 lines of type, yet
only seven are part of the executable C# program, and the only line that actually does anything
is the shaded one that displays “Message”.
public class ClassWithOneExecutingLine
/* This class has only one line that executes */
{
public static void Main()
{
// The next line writes the message
System.Console.Out.WriteLine("Message"); // Comment
}
/* This program serves
to demonstrate that a program
can "look" a lot longer than it really is */
}
Figure 1-4 Using comments within a program
16
Copyright 2009 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
C H A P T E R O N E
»TWO TRUTHS AND A LIE: ADDING COMMENTS TO A PROGRAM
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. XML-documentation format comments use a special set of tags within angle brackets (< >).
The false statement is #1. Line comments start with two forward slashes (//) and continue to the end of the current line.
ELIMINATING THE REFERENCE TO Out
BY USING THE System NAMESPACE
A program can contain as many statements as you want. For example, the program in
Figure 1-5 produces the three lines of output shown in Figure 1-6. A semicolon separates
each program statement.
public class ThreeLines
{
public static void Main()
{
System.Console.Out.WriteLine("Line one");
System.Console.Out.WriteLine("Line two");
System.Console.Out.WriteLine("Line three");
}
}
Figure 1-5 A program that produces three lines of output
Figure 1-6 Output of ThreeLines program
The program in Figure 1-5 shows a lot of repeated code—the phrase System.Console.Out.
WriteLine appears three times. When you use the name of the object Out, you are indicating
the console screen. However, Out is the default output object. That is, if you write
System.Console.WriteLine("Hi"); without specifying a Console object, the message
“Hi” goes to the default Console object, which is Out. Most C# programmers usually use
the WriteLine() method without specifying the Out object.
17
Copyright 2009 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
A FIRST PROGRAM USING C#
When you need to repeatedly use a class from the same namespace, you can shorten the
statements you type by using a clause that indicates a namespace where the class can be
found. You use 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 and Out were both repeated with each WriteLine() statement.
using System;
public class ThreeLines
{
public 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
and no explicit reference to the Out object
NOT RECOMMENDED: USING AN ALIAS
At this point, the clever programmer will say, “I’ll shorten my typing tasks even further by
typing using System.Console; at the top of my programs, and producing output with
statements like WriteLine("Hi");.” However, using cannot be used with a class name like
System.Console—only with a namespace name like System. Another option is to assign an
alias to a class with a using clause. An alias is an alternative name for a class. You might
assign one as a convenience when a fully qualified class name is very long. For example,
Figure 1-8 shows a program that uses an alias for System.Console (see shaded statement).
The lines of code within the program are shorter, but more difficult for another programmer
to read. In general, and especially while you are learning C#, you should avoid using aliases if
your intention is simply to reduce typing.
using SC = System.Console;
public class ThreeLines
{
public static void Main()
{
SC.WriteLine("Line one");
SC.WriteLine("Line two");
SC.WriteLine("Line three");
}
}
This alias is not conventional
and makes the program harder
for other programmers to
understand.
Figure 1-8 Using an alias for System.Console—a technique that is not recommended
18
Copyright 2009 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
C H A P T E R O N E
TWO TRUTHS AND A LIE: ELIMINATING THE REFERENCE TO Out BY
»USING
THE System NAMESPACE
1. Most C# programmers usually use the WriteLine() method without specifying the Out object.
2. 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.
3. Whenever possible, you should use aliases to make your programs as concise as you can.
The false statement is #3. You might assign an alias as a convenience when a fully qualified class name is very long.
However, using an alias makes your programs more difficult for other programmers to read. In general, and especially
while you are learning C#, avoid using aliases if your intention is simply to reduce typing.
WRITING AND COMPILING
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 (called the source code) into intermediate
language (IL).
2. The C# just in time (JIT) compiler must translate the intermediate code into executable
code.
»
NOTE When you compile a C# program, you translate your source code into intermediate language. The JIT
compiler converts IL instructions into native code at the last moment, and appropriately for each different type of
computer on which the code might eventually be executed. In other words, the same set of IL can be JIT-compiled and
executed on any supported architecture.
»
NOTE Some developers say that languages like C# are “semi-compiled.” That is, instead of being translated i
mmediately 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 machine on which the program is running.
You can perform these steps from the command line or within the Integrated Development
Environment (IDE) that comes with Visual Studio. Both methods produce the same results;
the one you use is a matter of preference. You might prefer the simplicity of the command
line because you do not work with multiple menus and views. Additionally, if you want to
pass command-line arguments to a program, you must compile from the command line. On
the other hand, many programmers prefer using the IDE because it provides features such
as color-coded keywords and automatic statement completion.
COMPILING CODE FROM THE COMMAND PROMPT
To compile your source code from the command line, you first locate the command prompt.
For example, in Windows Vista, you click Start, All Programs, Accessories, and Command
19
Copyright 2009 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
A FIRST PROGRAM USING C#
Prompt. As shown in Figure 1-9, you type csc at the command prompt, followed by the name
of the file that contains the source code. The command csc stands for “C Sharp compiler.”
For example, to compile a file named ThreeLines.cs, you would type csc ThreeLines.cs
and then press the Enter key. One of three outcomes will occur:
» You receive an operating system error message such as “Bad command or file name” or
»
»
“csc is not recognized as an internal or external command, operable program or batch
file”.
You receive one or more program language error messages.
You receive no error messages (only a copyright statement from Microsoft), indicating
that the program has compiled successfully.
Figure 1-9 Attempt to compile a program from the root directory at the command line, and error message received
If you receive an operating system message such as “csc is not recognized . . . ,” or “Source
file . . . could not be found,” it may mean that:
» You misspelled the command csc.
» You misspelled the filename.
» You forgot to include the extension .cs with the filename.
» You didn’t use the correct case. If your filename is ThreeLines.cs, then csc
threelines.cs will not compile.
» You are not within the correct subdirectory or folder on your command line. For example,
»
»
Figure 1-9 shows the csc command typed in the root directory of the C drive. If the
ThreeLines.cs file is stored in a folder on the C drive, then the command shown will not
work.
The C# compiler was not installed properly.
You need to set a path command.
To set a path command, you must locate the C# compiler on your hard disk. To locate the C#
compiler whose name is csc.exe, use one of the following techniques:
» In either Vista or Windows XP, double-click Computer (or My Computer), double-click
the C drive, double-click the Windows folder, double-click the Microsoft.NET folder,
double-click the Framework folder, double-click the v3.5 folder, and confirm that
20
Copyright 2009 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
C H A P T E R O N E
»
»
»
csc.exe is a program listed there. C# should be installed in this location if the program
was installed using the default options.
If the compiler can’t be found in the default location, click Start in Vista, click Search,
click the button to the right of Advanced Search, and then click the list box next to
Location. From the drop-down list, click OS (C:) or the name of your local hard drive.
Check the box next to “Include non-indexed, hidden, and system files.” In the Name
dialog box, type csc.exe, then click Search.
If the compiler can’t be found in the default location, click Start in Windows XP, click
Search, and choose All Files or Folders to look for the file named csc.exe.
If your search fails to find csc.exe, you need to obtain and install a copy of the C# compiler.
For more information, visit http://msdn2.microsoft.com/en-us/vcsharp/default.aspx.
If you do find the csc.exe file, type path = at the command line, followed by the complete
path name that describes where csc.exe is stored; then try to compile the ThreeLines
program again. For example, if C# was stored in the default location, you might type the
following:
path = c:\Windows\Microsoft.NET\Framework\v3.5
Press Enter. Next, type csc ThreeLines.cs and press Enter again.
»
NOTE In Windows XP, you also can change the path command if you are the System Administrator on the local
computer. Click Start, click Control Panel, and then double-click System. In Vista, click Advanced system settings, then
click Continue. In either Vista or Windows XP, click Environment Variables on the Advanced tab, then scroll through the list
of variables for the path command. If it is there, click it and click Edit; if not, click New. Either way, type the new path variable value in the dialog box that appears. Then click OK twice and close the System Properties window.
If you receive a programming language error message, it means that the source code contains
one or more syntax errors. A syntax error occurs when you introduce typing errors into your
program. For example, if the first line of your program begins with “Public” (with an uppercase
P), you will get an error message such as “A namespace does not directly contain
members such as fields or methods” after compiling the program, because the
compiler won’t recognize ThreeLines as a class with a Main() method. If this problem
occurs, you must reopen the text file that contains the source code, make the necessary
corrections, save the file, and compile it again.
»
NOTE The C# compiler issues warnings as well as errors. A warning is less serious than an error; it means that the
compiler has determined you have done something unusual, but not illegal. If you have purposely introduced a warning
situation to test a program, then you can ignore the warning. Usually, however, you should treat a warning message just
as you would an error message and attempt to remedy the situation.
If you receive no error messages after compiling the code, then the program compiled
successfully and a file with the same name as the source code—but with an .exe extension—is
created and saved in the same folder as the program text file. For example, if ThreeLines.cs
compiles successfully, then a file named ThreeLines.exe is created.
21
Copyright 2009 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
A FIRST PROGRAM USING C#
To run the program from the command line, you simply type the program name—for
example, ThreeLines. You can also type the full filename, ThreeLines.exe, but it is not
necessary to include the extension.
COMPILING CODE FROM WITHIN
THE VISUAL STUDIO IDE
As an alternative to using the command line, you can compile and write your program within
the Visual Studio IDE. This approach has several advantages:
» Some of the code you need is already created for you.
» The code is displayed in color, so you can more easily identify parts of your program.
Reserved words appear in blue, comments in green, and identifiers in black.
» If error messages appear when you compile your program, you can double-click an error
»
message and the cursor will move to the line of code that contains the error.
Other debugging tools are available. You will become more familiar with these tools as
you develop more sophisticated programs.
Figure 1-10 shows a program written in the editor of the Visual Studio IDE. You can see that
the environment looks like a word processor, containing menu options such as File, Edit, and
Help, and buttons with icons representing options such as Save, Copy, and Paste. You will
learn about some of these options later in this chapter and continue to learn about more of
them as you work with C# in the IDE.
Figure 1-10 ThreeLines program as it appears in Visual Studio Express Edition
22
Copyright 2009 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
C H A P T E R O N E
»TWO TRUTHS AND A LIE: WRITING AND COMPILING A C# PROGRAM
1. After you write and save a program, you must compile it into intermediate language and then the C# just in time (JIT)
compiler must translate the intermediate code into executable code.
2. You can compile and execute a C# program from the command line or within the Integrated Development Environment
(IDE) that comes with Visual Studio.
3. Many programmers prefer to compile their programs from the command line because it provides features such as
color-coded keywords and automatic statement completion.
The false statement is #3. Programmers who prefer the command line prefer its simplicity. Programmers who prefer the
Visual Studio IDE prefer the color-coded keywords and automatic statement completion.
ALTERNATE WAYS TO WRITE
A Main() METHOD
Figures 1-8 and 1-10 show a Main() method with the following header:
public static void Main()
Using the return type void and listing nothing between the parentheses that follow Main is
just one way to write a Main() method header in a program. (However, it is the first way
listed in the C# documentation, and it is the convention that this book uses.)
Figure 1-11 shows an alternate way to write the Main() method header in the ThreeLines
class. The shaded phrase string[] args is a parameter to the Main() method. A string is
a data type that can hold a series of characters. The square brackets indicate that you can
include a list or array of those strings. In Figure 1-11, args is a programmer-chosen name
for the memory location where the list of strings is stored. Although you can use any
using System;
public class ThreeLines
{
public static void Main(string [] args)
{
Console.WriteLine("Line one");
Console.WriteLine("Line two");
Console.WriteLine("Line three");
}
}
»NOTE
In Chapter 6, you
will create other
methods that can
accept parameters.
»NOTE
You will learn more
about the string
data type in
Chapter 2. You
will learn more
about how to use
command-line
arguments in
Chapter 5 when
you study arrays.
Figure 1-11 A Main() method with a string[] args parameter
23
Copyright 2009 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
A FIRST PROGRAM USING C#
identifier, args is traditional. Use this format for the Main() method header if you need to
access command-line arguments passed in to your application. For example, if you issued
the following command, then the strings “yes”, “no”, and “maybe” would be stored at the
memory location named args:
cs ThreeLines yes, no, maybe
»NOTE
In particular, Java programmers might prefer the version of Main() that includes the string[] args
parameter because, conventionally, they write their main methods with the same parameter.
Even if you do not need access to command-line arguments, you can still use the version of
the Main() method header that references them. You should use this form for your Main()
method headers if your instructor at school or supervisor at work indicates you should follow
this convention.
Some programmers prefer to write the ThreeLines class Main() method as shown in
Figure 1-12. The shaded keyword int replaces void in the method header, indicating that the
method returns an integer value. If you use this form of method header, then the last statement
in the Main() method must be a return statement that returns an integer. By convention, a
return value of 0 means an application ended without error. The value might be used by
your operating system or another program that uses your program.
using System;
public class ThreeLines
{
public static int Main(string[] args)
{
Console.WriteLine("Line one");
Console.WriteLine("Line two");
Console.WriteLine("Line three");
return 0;
}
}
Figure 1-12 A Main() method with an int return type
»NOTE
You will learn more about the int data type in Chapter 2. You will learn more about how to return values
from methods in Chapter 6.
»NOTE
In particular, C++ programmers might prefer the version of Main() that returns an int because, conventionally,
they write their main methods with an int return type.
24
Copyright 2009 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
C H A P T E R O N E
Even if you do not need to use a return value from a Main() method, you can still use the
version of the Main() method header that uses a return value. You should use this form for
your Main() method headers if your instructor at school or supervisor at work indicates
you should follow this convention.
»TWO TRUTHS AND A LIE: ALTERNATE WAYS TO WRITE A Main() METHOD
1. In C#, a Main() method header can be written public static void Main().
2. In C#, a Main() method header can be written public static void Main(string[] args).
3. In C#, a Main() method header can be written public static int main(string args).
The false statement is #3. In C#, a Main() method header can be written as shown in either of the first two examples,
or as public static int Main(string[] args). That is, Main() must be capitalized and string must be
followed by a pair of square brackets.
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 so you can compile and execute
it. It is a tradition among programmers that the first program you write in any language
produces “Hello, world!” as its output. You will create such a program now. To create a
C# program, you can use the editor that is included as part of the Microsoft Visual
Studio IDE. (The C# compiler, other language compilers, and many development tools
also are contained in the IDE, which is where you build, test, and debug your C#
application.) Alternatively, you can use any text editor. 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
To write your first C# program:
1. Start any text editor, such as Notepad, and open a new document, if necessary.
2. Type the class header public class Hello. In this example, the class name is
Hello.
3. Press the Enter key and type the class-opening curly brace {. Press Enter again to start a
new line.
4. Type three spaces to indent, and write the Main() method header:
public static void Main()
Press Enter to start a new line.
5. Type three spaces to indent, type {, and then press Enter.
25
Copyright 2009 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
A FIRST PROGRAM USING C#
6. Type six spaces so the next statement will be indented within the curly braces of the
Main() method. Type the one executing statement in this program:
System.Console.Out.WriteLine("Hello, world!");
7. Press Enter, type three spaces, type a closing curly brace for the Main() method, press
Enter, and type a closing curly brace for the class. Your code should look like Figure 1-13.
public class Hello
{
public static void Main()
{
System.Console.Out.WriteLine("Hello, world!");
}
}
Figure 1-13 The Hello class
8. Choose a location that is meaningful to you to save your program. For example, you might
create a folder named C# on your hard drive. Within that folder, you might create a folder
named Chapter.01 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 of your school’s
server, or you might prefer to store your examples on a USB drive or other portable storage
media. 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.
»
NOTE 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 type quotes surrounding a filename (as in “Hello.cs”), most editors will save the file as you specify,
without adding their own extension. If you use a word-processing program as your editor, select the option to save the
file as a plain text file.
COMPILING AND EXECUTING A PROGRAM
FROM THE COMMAND LINE
To compile and execute your Hello program from the command line:
1. Go to the command prompt on your system. For example, in Vista or Windows XP, click
Start, click All Programs, click Accessories, and click Command Prompt. Change the
current directory to the name of the folder that holds your program.
If your command prompt indicates a path other than the one you want, you can type cd\
and then press Enter to return to the root directory. You can then type cd to change the
path to the one where your program resides. For example, if you stored your program file
in a folder named Chapter.01 within a folder named C#, then you can type the following:
cd C#\Chapter.01
The command cd is short for change directory.
26
Copyright 2009 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
C H A P T E R O N E
2. Type the command that compiles your program:
csc Hello.cs
If you receive no error messages and the prompt returns, it means that the compile operation
was successful, that a file named Hello.exe has been created, and that you can execute the
program. If you do receive error messages, check every character of the program you
typed to make sure it matches Figure 1-13. Remember, C# is case sensitive, so all casing
must match exactly. When you have corrected the errors, repeat this step to compile the
program again.
3. You can verify that a file named Hello.exe was created in several ways:
» At the command prompt, type dir to view a directory of the files stored in the current
folder. Both Hello.cs and Hello.exe should appear in the list. See Figure 1-14.
Figure 1-14 Directory of Chapter.01 folder after compiling Hello.cs
» Use Windows Explorer to view the contents of the Chapter.01 folder, verifying that two
Hello files are listed.
» Double-click the My Computer icon, find and double-click the Chapter.01 folder, and
verify that two Hello files are listed.
4. At the command prompt, type Hello, which is the name of the program (the name of the
executable file), and then press Enter. Alternatively, you can type the full filename Hello.
exe, but typing the .exe extension isn’t necessary. The output should look like Figure 1-15.
Figure 1-15 Output of the Hello application
27
Copyright 2009 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
A FIRST PROGRAM USING C#
»
NOTE You can use the /out compiler option between the csc command and the name of the .cs file to indicate
the name of the output file. For example, if you type csc /out:Hello.exe Hello.cs, you create an output file
named Hello.exe. By default, the name of the output file is the same as the name of the .cs file. Usually, this is your
intention, so most often you omit the /out option. You will learn to add other options to the command line in Chapter 3.
COMPILING AND EXECUTING A PROGRAM
USING THE VISUAL STUDIO IDE
Next, you will use the C# compiler environment to compile and execute the same Hello
program you ran from the command line.
To compile and execute the Hello program in the Visual Studio IDE:
1. Within the text editor you used to write the Hello program, select the entire program
text. In Notepad, for example, you can highlight all the lines of text with your mouse (or
press Ctrl+A). Next, copy the text to the Clipboard for temporary storage by clicking Edit
on the menu bar and then clicking Copy (or by pressing Ctrl+C). You’ll paste the text in a
few steps.
2. Open Visual Studio. If there is a shortcut icon on your desktop, you can double-click it.
Alternatively, in Vista or Windows XP, you can click the Start button and then click All
Programs. Then you can click Microsoft Visual C# 2008 Express Edition.
»
NOTE The instructions and screen images in this chapter assume you are using the Express Edition of C#. If you
are using the Professional Edition, some screen elements will have minor differences. For example, in the Professional
Edition, you open Visual Studio by clicking Microsoft Visual Studio 2008. Also, when you are working in Visual Studio, the
title bar looks different.
3. On the Start Page, click File on the menu bar, then click New Project, as shown in
Figure 1-16.
Figure 1-16 Selecting a new project
28
Copyright 2009 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
C H A P T E R O N E
4. In the New Project window, click Console Application. Enter Hello as the name for this
project (see Figure 1-17). Click OK. Visual C# creates a new folder for your project named
after the project title.
Figure 1-17 Entering the project name
»
NOTE In Visual Studio Professional 2008, you click Visual C# under Project types and then click Console
Application under Templates.
5. The Hello application editing window appears, as shown in Figure 1-18. A lot of code is
already written for you in this window, including some using statements, a namespace
named Hello, a class named Program, and a Main() method. You could leave the class
header, Main() method header, and other features, and just add the specific statements
you need. You would save a lot of typing and prevent typographical errors. But in this case,
you have already written a functioning Hello program, so you will replace the prewritten
code with your Hello code. Select all the code in the editor window by highlighting it
with your mouse (or by pressing Ctrl+A). Then press Delete. Paste the previously copied
Hello program into the editor by pressing Ctrl+V (or by clicking Edit on the menu bar
and then clicking Paste).
29
Copyright 2009 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
A FIRST PROGRAM USING C#
»NOTE
When you select
the code in the
editor window, be
sure to delete it
and not cut it. If
you cut it, then the
same text will be
reinserted when
you select Paste.
Figure 1-18 The Hello application editing window
6. Save the file by clicking File on the menu bar and then clicking Save Hello, or by clicking
the Save button on the toolbar. Your screen looks like Figure 1-19.
Figure 1-19 The Hello application in the IDE
30
Copyright 2009 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
C H A P T E R O N E
»
NOTE The tab that contains Program.cs does not contain an asterisk if your program has been saved. As soon as
you change even one character in the editor, an asterisk appears in the Program.cs tab, indicating that a change has been
made but not yet saved.
7. To compile the program, click Build on the menu bar and then click Build Solution.
(Alternatively, you can press F6.) You should receive no error messages, and the words
“Build succeeded” should appear near the lower-left edge of the window.
8. Click Debug on the menu bar and then click Start Without Debugging. Figure 1-20
shows the output; you see “Hello, world!” followed by the message “Press any key to
continue”. Press any key to dismiss the output screen.
»
NOTE If the output appears but quickly disappears before you can read it, you can add a statement to the program
to hold the output screen until you press Enter. Position your insertion point at the end of the WriteLine() statement,
press Enter to insert a new line, and type System.Console.ReadLine();. Then build and start the program again.
Figure 1-20 Output of the Hello application in Visual Studio
9. Close Visual Studio by clicking File on the menu bar and then clicking Exit, or by clicking
the Close box in the upper-right corner of the Visual Studio window. When you receive a
message “Do you want to save or discard changes to the current solution?”, click Save.
In the Save Project window, you can select a folder location to save the project, as shown
in Figure 1-21.
Figure 1-21 The Save Project window
10. When you create a C# program using an editor such as Notepad and compiling with the
csc command, only two files are created—Hello.cs and Hello.exe. When you create a C#
program using the Visual Studio editor, many additional files are created. You can view
their filenames in several ways:
» At the command prompt, type dir to view a directory of the files stored in the folder
where you saved the project (for example, your Chapter.01 folder). Within the folder, a
31
Copyright 2009 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
A FIRST PROGRAM USING C#
»
new folder named Hello has been created. Type the command cd Hello to change the
current path to include this new folder, then type dir again. You see another folder
named Hello. Type cd Hello again, and dir again. Figure 1-22 shows the output using
this method; it shows several folders and files.
Double-click the Computer icon (or My Computer in Windows XP), find and doubleclick the correct drive, select the C# folder and the Chapter.01 folder (or the path you
are using), double-click the Hello folder, and view the contents. Double-click the
second Hello folder and view the contents there too. Figure 1-23 shows the second
Hello folder contents.
Figure 1-22 Directory listing for Hello folder
32
Copyright 2009 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
C H A P T E R O N E
Figure 1-23 Contents of the C#/Chapter.01/Hello/Hello folder
» Use Windows Explorer to view the contents of the Hello folders within the Chapter.01
folder. In Vista, click Start, All Programs, Accessories, and Windows Explorer.
Then, in the left panel, select Desktop and Computer. The remaining navigation steps
are the same as using Computer from the desktop in the last bullet.
The innermost Hello folder contains a bin folder, an obj folder, a Properties folder, and
additional files. If you explore further, you will find that the bin folder contains Debug and
Release folders, which include additional files. Using the Visual Studio editor to compile your
programs creates a lot of overhead. These additional files become important as you create
more sophisticated C# projects. For now, while you learn C# syntax, using the command line
to compile programs is simpler.
»NOTE
If you are using a
version of Visual
Studio other than
2008 Express, your
folder configuration
might be slightly
different.
»
NOTE If you followed the earlier instructions on compiling a program from the command line, and you used the
same folder when using the IDE, you will see the additional Hello.cs and Hello.exe files in your folder. These files will have
an earlier time stamp than the files you just created. If you were to execute a new program from within Visual Studio without saving and executing it from the command line first, you would not see these two additional files.
DECIDING WHICH METHOD TO USE
When you write, compile, and execute a C# program, you can use either the command line or
the Visual Studio IDE. You would never need to use both. You might prefer using an editor
with which you are already familiar (such as Notepad) and compiling from the command line
because only two files are generated, saving disk space.
On the other hand, the IDE provides many useful features, such as automatic statement
completion. For example, if you type System and a dot, then a list of choices is displayed, and
you can click Console instead of typing it. Similarly, after the dot that follows Console, a list
of choices is displayed from which you can select Out. Additionally, in the IDE, words are
displayed using different colors based on their category; for example, one color is used for
C#-reserved words and a different color for literal strings. It is also easier to correct many
errors using the IDE. When compiler errors or warnings are issued, you can double-click
the message, and the cursor jumps to the location in the code where the error was detected.
33
Copyright 2009 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
A FIRST PROGRAM USING C#
Another advantage to learning the IDE is that if you use another programming language in
Visual Studio (C++ or Visual Basic), the environment will already be familiar to you.
The C# language works the same way, no matter what method you use to compile your
programs. Everything you learn in the next chapters about input, output, decision making,
loops, and arrays will work the same way, regardless of the compilation technique you use.
You can use just one technique, or compile some programs in each environment as the mood
strikes you. You can also mix and match techniques if you prefer. For example, you can use
an editor you like to compose your programs, then paste them into the IDE to execute them.
Although any program can be written using either compilation technique, when you write
graphical user interface (GUI) applications that use existing objects such as message boxes
and buttons, you will find that the extensive amount of code automatically generated by the
IDE is very helpful. For the first nine chapters of this book, you are encouraged to use
whichever compilation technique you prefer. In Chapter 10, you will be encouraged to use
the IDE to take advantage of its many time-saving features.
ADDING COMMENTS TO A PROGRAM
To add comments to your program:
»NOTE
In Visual Studio
Professional, you
click File, point to
Open, and click
Project/Solution.
1. If you prefer compiling programs from the command line, then open the Hello.cs file in
your text editor. If you prefer compiling programs from within Visual Studio, then open
Visual Studio, click File, click Open Project, browse for the correct folder, double-click
the Hello folder, and then double-click the Hello file. In the Solution Explorer at the side
of the screen, double-click Hello.cs, as shown in Figure 1-24.
Figure 1-24 Visual C# and the Solution Explorer window
34
Copyright 2009 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
C H A P T E R O N E
»
NOTE If you do not see the Solution Explorer window in Visual Studio, click the Solution Explorer icon on the
toolbar (shown at right). Alternatively, from the main menu, choose View and then Solution Explorer. The Solution
Explorer displays the various files that make up a project.
2. Position your cursor at the top of the file, press Enter to insert a new line, press the Up
arrow key to go to that line, and then type the following comments at the top of the file.
Press Enter after typing each line. Insert your name and today’s date where indicated.
// Filename Hello.cs
// Written by <your name>
// Written on <today’s date>
3. Scroll to the line that reads public static void Main() and press Enter to start a
new line. Then press the Up arrow; in the new blank line, aligned with the start of the
Main() method header, type the following block comment in the program:
/*
This program demonstrates the use of
the WriteLine() method to print the
message Hello, world! */
4. Save the file, replacing the old Hello.cs file with this new, commented version.
5. If you prefer to compile programs from the command line, type csc Hello.cs at the
command line. When the program compiles successfully, execute it with the command
Hello. If you prefer compiling and executing programs from within Visual Studio, click
Debug and Start Without Debugging. Adding program comments makes no difference
in the execution of the program.
CHAPTER SUMMARY
» A computer program is a set of instructions that you write to tell a computer what to do.
»
»
»
Programmers write their programs, then use a compiler to translate their high-level
language statements into intermediate language and machine code. A program works
correctly when both its syntax and logic are correct.
Procedural programming involves creating computer memory locations, called variables,
and sets of operations, called methods. In object-oriented programming, you envision
program components as objects that are similar to concrete objects in the real world;
then you manipulate the objects to achieve a desired result. Objects exist as members of
classes and are made up of states and methods.
The C# programming language was developed as an object-oriented and componentoriented language. It contains many features similar to those in Visual Basic, Java,
and C++.
To write a C# program that produces a line of console output, you must pass a literal
string as an argument to the System.Console.Out.WriteLine() method. System is
a namespace, Console is a class, and Out is an object. The WriteLine() method call
appears within the Main() method of a class you create.
35
Copyright 2009 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
A FIRST PROGRAM USING C#
» You can define a C# class or variable by using any name or identifier that begins with an
underscore or a letter, contains only letters or digits, and is not a C#-reserved keyword.
» Program comments are nonexecuting statements that you add to document a
»
»
»
program or to disable statements when you test a program. There are three types
of comments in C#: line comments that start with two forward slashes ( // ) and
continue to the end of the current line, block comments that start with a forward
slash and an asterisk ( /*) and end with an asterisk and a forward slash (*/ ), and
XML-documentation comments.
When you need to repeatedly use a class from the same namespace, you can shorten the
statements you type by using a clause that indicates a namespace where the class can be
found.
To create a C# program, you can use the Microsoft Visual Studio environment. You can
also use any text editor, such as Notepad, WordPad, or any word-processing program.
After you write and save a program, you must compile the source code into intermediate
and machine language.
You have multiple options for writing the Main() method header; the format you use
depends on your need for command-line arguments and the conventions you prefer in
your working environment.
KEY TERMS
A computer program is a set of instructions that you write to tell a computer what to do.
Machine language is the most basic circuitry-level language.
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.
A language’s syntax is its set of rules.
A compiler is a computer program that translates high-level language statements into
machine code.
A syntax error is an error that occurs when a programming language is used incorrectly.
The logic behind any program involves executing the various statements and methods in the
correct order to produce the desired results.
Semantic errors are the type of logical errors that occur when you use a correct word in the
wrong context.
Debugging a program is the process of removing all syntax and logical errors from the
program.
A procedural program is created by writing a series of steps or operations to manipulate
values.
Variables are named computer memory locations that hold values that might vary.
An identifier is the name of a program component such as a variable, class, or method.
36
Copyright 2009 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
C H A P T E R O N E
Camel casing is a style of creating identifiers in which the first letter is not capitalized, but
each new word is.
Pascal casing is a style of creating identifiers in which the first letter of all new words in a
variable name, even the first one, is capitalized.
Procedures or methods are compartmentalized program units that accomplish tasks.
A program calls or invokes methods.
Object-oriented programming is a programming technique that features objects, classes,
encapsulation, interfaces, polymorphism, and inheritance.
Objects are program elements that are instances of a class.
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.
The attributes of an object represent its characteristics.
The states of an object are the values of its attributes.
The properties of an object are its values.
The state of an object is the collective value of all its attributes at any point in time.
A class is a category of objects or a type of object.
Each object is an instance of a class.
Encapsulation is the technique of packaging an object’s attributes and methods into a
cohesive unit that can be used as an undivided entity.
A black box is a device you use without regard for the internal mechanisms.
An interface is the interaction between a method and an object.
Polymorphism is the ability to create methods that act appropriately depending on the
context.
Inheritance is the ability to extend a class so as to create a more specific class that contains
all the attributes and methods of a more general class; the extended class usually contains
new attributes or methods as well.
The C# programming language was developed as an object-oriented and componentoriented language. It exists as part of Visual Studio 2008, a package used for developing
applications for the Windows family of operating systems.
Primitive data is simple data, such as a number.
A literal string of characters is a series of characters that is used exactly as entered.
An argument or a parameter to a method represents information that a method needs to
perform its task. An argument is the expression used when you call a method, while a
parameter is an object or reference that is declared in a method definition; that is, where
the method instructions are written.
37
Copyright 2009 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
A FIRST PROGRAM USING C#
The WriteLine() method displays a line of output on the screen, positions the cursor on
the next line, and waits for additional output.
The Write() method displays a line of output on the screen, but the cursor does not
advance to a new line; it remains on the same line as the output.
A namespace is a scheme that provides a way to group similar classes.
The System namespace, which is built into your C# compiler, holds commonly used classes.
A method header includes the method name and information about what will pass into and
be returned from a method.
The method body of every method is contained within a pair of curly braces ({ }) and
includes all the instructions executed by the method.
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.
Keywords are predefined and reserved identifiers that have special meaning to the compiler.
An access modifier defines the circumstances under which a method or class can be
accessed; public access is the most liberal type of access.
In a method header, public is an access modifier that indicates other classes may use the
method.
In a method header, private is an access modifier that indicates other classes may not use
the method.
The reserved keyword static indicates that a method will be executed through a class and
not by an object.
In a method header, the keyword void indicates that the method does not return any value
when called.
A verbatim identifier is an identifier with an @ prefix.
Program comments are nonexecuting statements that you add to document a program.
When you comment out a statement, you turn it into a comment so that the compiler will
not execute its command.
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 at the end 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. They can also extend across as many lines as
needed.
XML-documentation format comments use a special set of tags within angle brackets to
create documentation from within a program.
You use a namespace with a using clause, or using directive.
38
Copyright 2009 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
C H A P T E R O N E
An alias is an alternative name for a class.
Source code is the statements you write when you create a program.
Intermediate language (IL) is the language into which source code statements are
compiled.
The C# just in time (JIT) compiler translates intermediate code into executable code.
A string is a data type that can hold a series of characters.
REVIEW QUESTIONS
1. A computer program written as a series of on and off switches is written in ____________ .
a. machine language
c. a high-level language
b. a low-level language
d. a compiled language
2. A program that translates high-level programs into intermediate or machine code
is a(n) ____________ .
a. mangler
c. analyst
b. compiler
d. logician
3. The grammar and spelling rules of a programming language constitute its ____________ .
a. logic
c. syntax
b. variables
d. vortex
4. Variables are ____________ .
a. procedures
c. grammar rules
b. named memory locations
d. operations
5. Programs in which you create and use objects that have attributes similar to their realworld counterparts are known as ____________ programs.
a. procedural
c. authentic
b. logical
d. object-oriented
6. Which of the following pairs is an example of a class and an object, in that order?
a. robin and bird
c. university and Harvard
b. chair and desk
d. oak and tree
39
Copyright 2009 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
A FIRST PROGRAM USING C#
7. The technique of packaging an object’s attributes into a cohesive unit that can be used as
an undivided entity is ____________ .
a. inheritance
c. polymorphism
b. encapsulation
d. interfacing
8. Of the following languages, which is least similar to C#?
a. Java
c. C++
b. Visual Basic
d. COBOL
9. A series of characters that appears within double quotation marks is a(n) ____________ .
a. parameter
c. argument
b. interface
d. literal string
10. The C# method that prints a line of output on the screen and then positions the cursor
on the next line is ____________ .
a. WriteLine()
c. DisplayLine()
b. PrintLine()
d. OutLine()
11. Which of the following is an object?
a. System
c. Out
b. Console
d. WriteLine
12. In C#, a scheme that groups similar classes is a(n) ____________ .
a. superclass
c. namespace
b. method
d. identifier
13. Every method in C# contains a ____________ .
a. header and a body
c. variable and a class
b. header and a footer
d. class and an object
14. Which of the following is a method?
a. namespace
c. Main()
b. public
d. static
15. Which of the following statements is true?
a. An identifier must begin with an underscore.
b. An identifier can contain digits.
c. An identifier must be no more than 16 characters long.
d. An identifier can contain only lowercase letters.
40
Copyright 2009 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
C H A P T E R O N E
16. Which of the following identifiers is not legal in C#?
a. per cent increase
c. HTML
b. annualReview
d. alternativetaxcredit
17. The text of a program you write is called _____________ .
a. object code
c. machine language
b. source code
d. executable documentation
18. Programming errors such as using incorrect punctuation or misspelling words are
collectively known as ____________ errors.
a. syntax
c. executable
b. logical
d. fatal
19. A comment in the form /* this is a comment */ is a(n) ____________ .
a. XML comment
c. executable comment
b. block comment
d. line comment
20. If a programmer inserts using System; at the top of a C# program, which of the
following can the programmer use as an alternative to
System.Console.Out.WriteLine("Hello");?
a. System("Hello");
c. Console.WriteLine("Hello");
b. WriteLine("Hello");
d. Console.Out("Hello");
EXERCISES
1. Indicate whether each of the following C# programming language identifiers is legal
or illegal.
a. WeeklySales
g. abcdefghijklmnop
b. last character
h. 23jordan
c. class
i. my_code
d. MathClass
j. 90210
e. myfirstinitial
k. year2008Budget
f. phone#
l. abfSorority
2. Name at least three attributes that might be appropriate for each of the following classes:
a. TelevisionSet
c. PatientMedicalRecord
b. EmployeePaycheck
41
Copyright 2009 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
A FIRST PROGRAM USING C#
3. Name a class to which each of these objects might belong:
a. your red bicycle
c. last month’s credit card bill
b. Albert Einstein
4. Write, compile, and test a program that displays your first name on the screen. Save the
program as Name.cs.
5. Write, compile, and test a program that displays your full name, street address, and city
and state on three separate lines on the screen. Save the program as Address.cs.
6. Write, compile, and test a program that displays your favorite quotation on the screen.
Include the name of the person to whom the quote is attributed. Use as many display
lines as you feel are appropriate. Save the program as Quotation.cs.
7. Write, compile, and test a program that displays a pattern similar to the following on the
screen:
X
XXX
XXXXX
XXXXXXX
X
Save the program as Tree.cs.
8. Write a program that displays your initials in a pattern on the screen. Compose each initial with six lines of smaller initials, as in the following example:
J
J
J
J
J
J
JJJJJJ
FFFFFF
F
FFF
F
F
F
Save the program as Initials.cs.
9. From 1925 through 1963, Burma Shave advertising signs appeared next to highways all
across the United States. There were always four or five signs in a row containing 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:
Shaving brushes
You’ll soon see ’em
On a shelf
In some museum
Burma Shave
42
Copyright 2009 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
C H A P T E R O N E
Find a classic Burma Shave rhyme on the Web and write a program that displays it. Save
the program as BurmaShave.cs.
DEBUGGING EXERCISES
Each of the following files in the Chapter.01 folder on your Student Disk 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 with “Fixed”. For example,
DebugOne1.cs will become FixedDebugOne1.cs.
a. DebugOne1.cs
c. DebugOne3.cs
b. DebugOne2.cs
d. DebugOne4.cs
UP FOR DISCUSSION
1. Using an Internet search engine, find at least three definitions for object-oriented
programming. (Try searching with and without the hyphen in object-oriented.) Compare
the definitions and compile them into one “best” definition.
2. What is the difference between a compiler and an interpreter? What programming
languages use each? Under what conditions would you prefer to use one over the other?
3. What is the image of the computer programmer in popular culture? Is the image
different in books than in TV shows and movies? Would you like a programmer image
for yourself, and if so, which one?
43
Copyright 2009 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Copyright 2009 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.