Tuesday, January 14, 2014

 C# uses some notations that might appear strange to non programmers. We begin by con-
side ring a simple program that displays a line of text. The program and its output are shown
in Fig. 3.1. The program is followed by an output window that displays the program’s 
results. When you execute this program, the output will appear in a console window.



          This program illustrates several important features of C#. All programs we present in
this book will include line numbers for the reader’s convenience; these line numbers are not
part of the C# programs. Line 10 in Fig. 3.1 does the “real work” of the program, displaying
the phrase Welcome to C# Programming! on the screen. 
          Line 1 begins with //, indicating that the remainder of the line is a comment. Program-
mers insert comments to document and improve the readability of their code. Comments
also help other people read and understand your programs. This comment simply indicates
the figure number and file name for this program. We begin each program in this book in
this manner. In this case, we have named the file Welcome1.cs. A comment that begins
with // is called a single-line comment, because the comment terminates at the end of the
line. Single-line comments can be placed almost anywhere in the program.
          There is also a syntax for writing multiple-line comments. A multiple-line comment,
such as

/* This is a multiple–line 
   comment. It can be
   split over many lines */

          begins with delimiter /* and ends with delimiter */. All text between these delimiters is
treated as a comment and is ignored by the compiler. In the Visual Studio .NET IDE, all
comment text appears in green. Comments of the form // and /* … */ are ignored by the
compiler; therefore, they do not cause the computer to perform any action when the pro-
gram executes.

Common Programming Error 3.1
          Forgetting one of the delimiters of a multiple-line comment is a syntax error. A syntax error
is caused when the compiler cannot recognize a statement. The compiler normally issues an
error message to help the programmer locate and fix the incorrect statement. Syntax errors
are violations of the language rules. Syntax errors are also called compile errors, compile-
time errors or compilation errors because they are detected during the compilation phase. A
program cannot compile or execute until all the syntax errors are corrected. 

Software Engineering Observation 3.1
          Visual Studio will often times catch syntax errors as you are creating the program, even be-
fore the program is compiled. Look out for red jagged lines that may appear directly below

a syntax error.                

         C# uses the same syntax as the C programming language for multiple-line comments
(/*…*/) and the same syntax as C++ for single-line comments (//). C# programmers
generally use C++-style single-line comments, instead of C-style comments. Throughout

this book, we use mostly C++-style single-line comments.

Good Programming Practice 3.1
Every program should begin with one or more comments that describe the program’s purpose.  

         Line  4  (known  as a  using  directive) is  generated  by  the Visual  Studio  IDE and
declares that the program uses features in the System namespace. A namespace groups
various C# features into related categories. One of the great strengths of C# is that C# pro-
grammers can use the rich set of namespaces provided by the .NET framework. These
namespaces  contain  code  that  programmers  can  reuse,  rather  than  “reinventing  the
wheel.” This makes programming easier and faster. The namespaces that are defined in
the  .NET  Framework  contain  preexisting  code  known  as  the  .NET  Framework  Class
Library. An example of one of the features in namespace System is Console, which
we discuss momentarily. The various features are organized into namespaces that enable
programmers  to  locate  them  easily.  We  discuss  many  namespaces  and  their  features
throughout the book.

         Line  5  is  a  blank  line.  Programmers  often  use  blank  lines  and  space  characters
throughout a program to make the program easier to read. Collectively, blank lines, space
characters, newline characters and tab characters are known as whitespace (space charac-
ters and tabs are known specifically as whitespace characters). Newline characters charac-
ters  are  “special  characters”  that  indicate  when  to  position  the  output  cursor  at  the
beginning of the next line in the console window to continue output. The compiler ignores
blank lines, tabs and extra spaces that separate language elements. Several conventions for
using whitespace characters are discussed in this and subsequent chapters.   

      Good Programming Practice 3.2
         Use blank lines, space characters and tab characters in a program to enhance program read-
ability.                                                                                                                                      3.2
           Lines 6–12 define our first class (these lines collectively are called a class definition).
C# programs consist of pieces called classes, which are logical groupings of members (e.g.,
methods) that simplify program organization. These methods (which are like functions in
procedural programming languages) perform tasks and return information when the tasks
are completed. A C# program consists of classes and methods created by the programmer
and of preexisting classes found in the Framework Class Library. Throughout this book, we
will teach the reader how to use both techniques in their programs. Every program in C#
consists  of  at  least  one  class  definition  that the  programmer  defines.  These  classes  are
known as programmer-defined classes. In Chapter 8, Object-Based Programming, we dis-
cuss  programs  that  contain  multiple  programmer-defined  classes.  The  class  keyword
begins a class definition in C# and is followed immediately by the class name (Welcome1,
in this example). Keywords (or reserved words) are reserved for use by C# and always con-
sist of lowercase letters. (A complete table of C# keywords is presented in the next chapter.)
By convention, each word in a class name begins with an uppercase first letter and has an
uppercase letter for each word in the class name (e.g., SampleClassName). The name
of the class is known as an identifier, which is a series of characters consisting of letters,
digits, underscores ( _ ) and “at” symbols (@). Identifiers cannot begin with a digit and
cannot   contain   spaces.   Examples   of   valid   identifiers   are   Welcome1,   _value,
m_inputField1 and button7. The name 7button is not a valid identifier because it
begins with a digit, and the name input field is not a valid identifier because it contains
a space. The “at” character (@) can be used only as the first character in an identifier. C# is
case sensitive—uppercase and lowercase letters are considered different letters, so a1 and
A1 are different identifiers.

Common Programming Error 3.2
        C# is case sensitive. Not using the proper case for an identifier, e.g.,writing Total when the

identifier is total, is a compiler error.   

Good Programming Practice 3.3
         Always begin a class name with an uppercase first letter. This practice makes class names
easier to identify.                                                                                                                      3.3
       The left brace ({) at line 7 begins the body of the class definition. The corresponding
right brace (}) at line 12 ends the class definition. Notice that lines 8–11 in the body of the
class are indented. This is one of the spacing conventions mentioned earlier. Indentation
improves program readability. We define each spacing convention as a Good Program-
ming Practice.

Common Programming Error 3.3
If braces do not occur in matching pairs, a syntax error occurs.  
                                          
Good Programming Practice 3.4
When typing an opening left brace ({) in a program, immediately type the closing right brace
(}) then reposition the cursor between the braces to begin typing the body. This practice
helps prevent missing braces. Readers may notice that, when they type the closing brace, Vi-
sual Studio .NET makes both braces bold (as well as the first line of the class definition). This
is helpful in the creation of more complex programs that involve multiple sets of opening and
closing braces.     
                                                                                                                 
Good Programming Practice 3.5
Indent the entire body of each class definition one “level” of indentation between the left
brace ({) and the right brace (}) that delimit the class body. This emphasizes the structure
of the class definition and helps make the class definition easier to read. Visual Studio .NET
provides indentation in several places as programmers enter code.    

Line 8 is present in all C# console and Windows applications. These applications begin
executing at Main, which is known as the entry point of the program. The parentheses after
Main indicate that Main is a program building block, called a method. C# class definitions
normally contain one or more methods and C# applications contain one or more classes.
For a C# console or Windows application, exactly one of those methods must be called
Main, and it must be defined as shown on line 8; otherwise, the program is not executable.
Normally, a console applications’s Main method is defined as shown on line 8. Methods
are explained in detail in Chapter 6, Methods. For now, simply mimic Main’s first line in
each C# application.
The left brace ({) on line 9 begins the body of the method definition (the code which
will be executed as a part of our program). A corresponding right brace (}) terminates the
method  definition’s  body  (line  11).  Notice  that  the  line  in  the  body  of  the  method  is
indented between these braces.       

Good Programming Practice 3.6
         Indent the entire body of each method definition one “level” of indentation between the left
brace ({) and the right brace (}) that define the method body. This makes the structure of the
method stand out, improving the method definition’s readability. 
    
Line 10 instructs the computer to perform an action, namely, to print a series of char-
acters  contained  between  the  double  quotation  marks.  Characters  delimited  in  this
manner  are  called  strings,  character  strings  or  string  literals.  We  refer  to  characters
between double quotation marks generically as strings. Whitespace characters in strings
are  significant—the  compiler  does  not  ignore  these  characters  when  they  appear  in
strings.

           The Console class enables programs to output information to the computer’s stan-
dard output. Class Console provides methods that allow C# programs to display strings
and other types of information in the Windows command prompt.
          Method  Console.WriteLine  displays  (or  prints)  a  line  of  text  in  the  console
window. When Console.WriteLine completes its task, it positions the output cursor
(the location where the next character will be displayed) at the beginning of the next line in
the  console  window.  (This  is  similar  to  pressing  the  Enter  key  when  typing  in  a  text
editor—the cursor is repositioned at the beginning of the next line in the file.)
           The entire line, including Console.WriteLine, its argument in the parentheses
("Welcome  to C# Programming!") and the semicolon (;), is called a statement.
Every statement must end with a semicolon (known as the statement terminator). When this
statement executes, it displays the message Welcome to C# Programming! in the con-
sole window (Fig. 3.1).
           In C# statements we normally precede each class name with its namespace name and
a period. For example, line 10 would normally be      

          System.Console.WriteLine( "Welcome to C# Programming!" );

         for the program to run correctly. The using directive on line 4 eliminates the need to spec-
ify explicitly the namespace System when using classes in the namespace. This can save
time and confusion for programmers.

Common Programming Error 3.4

         Omitting the semicolon at the end of a statement is a syntax error. 
   
Testing and Debugging Tip 3.1
        When the compiler reports a syntax error, the error might not be on the line indicated by the
error message. First, check the line where the error was reported. If that line does not con-
tain syntax errors, check the lines that precede the one reportedTesting and Debugging Tip 3.1
When the compiler reports a syntax error, the error might not be on the line indicated by the
error message. First, check the line where the error was reported. If that line does not con-
tain syntax errors, check the lines that precede the one reported 

Now that we have presented this program to you, let us explain step-by-step how to

create and run it in Visual Studio. 

1.  Create  the  console  application.  Go  to  the  File  menu  and  choose  New,  then
Project…. A dialog will appear. In the left pane, choose Visual C# Projects;
from the right pane, choose Console Application. It is possible to specify other
information about the project in the bottom portion of this dialog (i.e., the name
and location of the project). After entering all the necessary information, click OK
to create the project. The project is created, and the code window is opened for
editing. The new application is shown in Fig. 3.2. Note that this is the same way
we created our application in Chapter 2, except that now we have chosen a console

application, instead of a Windows application.
         This application can be built (compiled) and executed, but will not do any-
thing until we add more code (this is done in Step 3). Let us briefly look at the code
generated for us by the IDE.
         Notice that this code contains features that we have not yet discussed. We
have done this for both display and clarity reasons—at this point in the book, this
code is neither required nor relevant to the discussion of this program. Much of
the extra code that the IDE provides is used either for documentation or to help
create graphical user interfaces. One of the things that the reader will no doubt no-
tice is that we do not show the lines directly above and below the class definition.
These lines are used to create namespaces, a topic that will be discussed in Chapter
8, Object-Based Programming. [Note: Several times early in this text, we ask the
reader to mimic certain C# features that we introduce. We do this especially when
it is not yet important to know all the details of a feature to use that feature in C#.
All programmers initially learn how to program by mimicking what other pro-
grammers have done. For each detail, we ask the reader to mimic, we indicate
where the full discussion will be presented later in the text.] The code for all ex-
amples in the book is included for the reader on our Web site www.deitel.com

under the Downloads/Resources link

2.Change the name of the program file. For the programs in this book, we usually
change the name of the code file. By default, the file is named Class1.cs. This
can be changed by right-clicking the name of the file in the Solution Explorer 
and selecting Rename. The reader can then enter a new name for the file, provid-

ed that this file ends in .cs (the file extension for C# code files).

3.  Complete the code. In the text editor, replace the comment

//
// TODO: Add code to start application here

//
       which is located within method Main with line 10 from Fig. 3.1 (this comment is
no longer necessary, for we are adding code to the program).

4. Run the program. We are now ready to compile and execute our program. To do
this, we simply follow the same steps that we executed for the example in Chapter
2. To compile the program, go to the Build menu and select Build Solution. If
the program contains no syntax errors, the preceding command creates a new file
called Welcome1.exe, containing the MSIL code for our application. To exe-
cute this  program, choose option Start Without Debugging1 in the  Debug
menu.

       Program execution begins with method Main, which is the entry point to the program.
Next,  the  statement  at  line  10  of  Main  displays  Welcome  to  C#  Programming!
Figure 3.3 shows result of executing the program.
       The  message  Welcome  to  C#  Programming!  can  be  displayed  via  multiple
method calls. Class Welcome2 of Fig. 3.4 uses two statements to produce the same output
shown in Fig. 3.3.
        Lines 10–11 of Fig. 3.4 display one line in the console window. The first statement
calls Console method Write to display a string. Unlike WriteLine, Write does not
position the output cursor at the beginning of the next line in the console window after dis-
playing its string. The next character displayed in the console window appears immediately
after the last character displayed with Write. Thus, when line 11 executes, the first char-
acter displayed (C) appears immediately after the last character displayed with Write (i.e.,
the space character after the word "to" in line 10). Each Write or WriteLine state-

ment resumes displaying characters from where the last Write or WriteLine stopped.


1.  Selecting Debug > Start Without Debugging causes the command window to prompt the user
to press a key after the program terminates, allowing the user to observe the program’s output. In
contrast, if we run this program using Debug > Start, as we did for the Windows application in
Chapter 2, a command window opens, the program displays the message Welcome to C# Pro-

gramming!, then the command window closes immediately.



        A single statement can display multiple lines by using newline characters. Recall that
these characters indicate when to position the output cursor at the beginning of the next line
in the console window to continue output. Figure 3.5 demonstrates using newline characters.
       Line 10 produces four separate lines of text in the console window. Normally, the char-
acters in a string are displayed exactly as they appear between the double quotes. However,
notice that the two characters “\” and “n” do not appear on the screen. The backslash (\)
is called an escape character. It indicates that a “special” character is to be output. When a
backslash is encountered in a string of characters, the next character is combined with the
backslash to form an escape sequence. This escape sequence \n is the newline character.
It causes the cursor (i.e., the current screen position indicator) to move to the beginning of

the next line in the console window. Some common escape sequences are listed in Fig. 3.6.




         Although the first several programs display output in the command prompt, most C#
applications use windows or dialogs to display output. As mentioned earlier, dialogs are
windows that typically display important messages to the user of an application. The .NET
Framework Class Library includes class MessageBox for creating dialogs. Class Mes-
sageBox is defined in namespace System.Windows.Forms. The program in Fig.3.7
displays the same string as Fig. 3.5 in a message dialog using class MessageBox.



         Many compiled classes in C# (including MessageBox) need to be referenced before
they can be used in a program. Depending on the type of application we create, classes may
be  compiled  into  files  with  a  .exe  (executable)  extension,  a  .dll  (or  dynamic  link
library) extension or one of several other extensions. Such files are called assemblies and
are the packaging units for code in C#. [Note: Assemblies can be comprised of many files
of several different types.] Namespaces group related classes together; the assembly is a
package containing the Microsoft Intermediate Language (MSIL) code that a project has
been  compiled  into,  plus  any  other  information  that  is  needed  for  these  classes.  The
assembly that we need to reference can be found in the Visual Studio .NET documentation
(also called the MSDN Documentation) for the class we wish to use. The easiest way to
access this information is to go to the Help menu in Visual Studio, and choose Index. The
reader can then type in the name of the class to access the documentation. Class Mes-
sageBox is located in assembly System.Windows.Forms.dll. As mentioned pre-
viously,  we  must  add  a  reference  to  this  assembly  to  use  class  MessageBox  in  our
program. Let us discuss an example of adding a reference to System.Windows.Forms
within the IDE.

Common Programming Error 3.5
Including a namespace with the using directive, but not adding a reference to the proper
assembly, results in a compiler error.           

     To  begin, make sure you  have an application open. Select the Add  Reference…
option  from  the Project menu, or right  click the References folder  in  the Solution
Explorer and select Add Reference… from the popup menu that appears. This opens
the Add Reference dialog (Fig. 3.8). Double click System.Windows.Forms.dll
to add this file to the Selected Components list at the bottom of the dialog, then click
OK. Notice that System.Windows.Forms now appears in the References folder of
the Solution Explorer (Fig. 3.8).
     After referencing the appropriate assembly and providing a using directive for the
corresponding  namespace  (line  5),  we  can  use  the  classes  in  that  namespace  (such  as
MessageBox).
     The reader may notice that we did not add any references to our previous programs.
Visual Studio adds a few common references when a project is created. Also, by default,
some assemblies do not require references. Class Console, for instance, is located in the
assembly mscorlib.dll, but a reference to this assembly is not required to use it.
     The System.Windows.Forms namespace contains many classes that help C# pro-
grammers define graphical user interfaces (GUIs) for their applications. GUI components
(e.g., buttons) facilitate both data entry by the user and the formatting or presenting of data
outputs to the user. For example, Fig. 3.9 is an Internet Explorer window with a bar con-
taining menus (File, Edit, View etc.). Below the menu bar there is a set of buttons, each
with a defined task in Internet Explorer. Below the buttons there is a text field in which the
user can type the location of a World Wide Web site to visit. To the left of the text field is
a label that indicates the purpose of the text field. The menus, buttons, text fields and labels
are part of Internet Explorer’s GUI. They enable users to interact with the Internet Explorer
program. C# contains classes that create the GUI components described here. Other classes
that create GUI components will be described in Chapters 12 and 13, Graphical User Inter-
faces: Part 1 and Graphical User Interfaces: Part 2.


          In Main, line 11 calls method Show of class MessageBox (Fig. 3.7). This method
takes a string as an argument and displays it to the user in a message dialog. Method Show
is called a static method. Such methods are always called by using their class name (in this
case, MessageBox) followed by a dot operator (.) and the method name (in this case,
Show). We discuss static methods in Chapter 8, Object-Based Programming. 
           Line 11 displays the dialog box shown in Fig. 3.10. The dialog includes an OK button
that allows the user to dismiss (close) the dialog. Positioning the mouse cursor (also called
the mouse pointer) over the OK button and clicking the mouse dismisses the dialog.
          C# allows large statements to be split over many lines. For example, we could have 
split the statement on line 11 into the following two lines:

MessageBox.Show(
"Welcome\nto\nC#\nprogramming!" );

     All statements end with a semicolon (;), so the compiler recognizes that these two lines
represent only one statement. However, you cannot split a statement in the middle of an
identifier (e.g., the class name) or a string.




Common Programming Error 3.6
Splitting a statement in the middle of an identifier or a string is a syntax error
.                   
     The user can close the dialog by clicking the OK button or the close box. Once this
occurs, the program terminates, because the Main method terminates.

                                                                                            

0 comments:

Post a Comment

Subscribe to RSS Feed Follow me on Twitter!