A Simple C# Application: Displaying a Line of Text

A Simple C# Application Displaying a Line of Text

Every time you use a computer, you execute various applications that perform tasks for you. For example, your e-mail application helps you send and receive e-mail, and your Web browser lets you view Web pages from Web sites around the world. Computer programmers create these applications.

Let us consider a simple application that displays a line of text. (Later in this section, we discuss how to compile and run an application.) The application and its output are shown in Fig. 3.1. The application illustrates several important C# language features. C# uses notations that may look strange to nonprogrammers. For your convenience, each program we present in this book includes line numbers, which are not part of actual C# code. In Section 3.3, we show how to display line numbers for your C# code in the IDE. We will soon see that line 10 does the real work of the applicationnamely, displaying the phrase Welcome to C# Programming! on the screen. We now consider each line of the applicationthis is called a code walkthrough.

Figure 3.1. Text-printing application.

1 // Fig. 3.1: Welcome1.cs 2 // Text-printing application. 3 using System; 4 5 public class Welcome1 6 { 7 // Main method begins execution of C# application 8 public static void Main( string[] args ) 9 { 10 Console.WriteLine( "Welcome to C# Programming!" ); 11 } // end method Main 12 } // end class Welcome1  

Welcome to C# Programming!

Line 1

// Fig. 3.1: Welcome1.cs

begins with //, indicating that the remainder of the line is a comment. Programmers insert comments to document applications and improve their readability. This helps people to read and understand applications. The C# compiler ignores comments, so they do not cause the computer to perform any action when the application is run. We begin every application with a comment indicating the figure number and the name of the file in which the application is stored.

A comment that begins with // is called a single-line comment, because it terminates at the end of the line on which it appears. A // comment also can begin in the middle of a line and continue until the end of that line (as in lines 7, 11 and 12).

Delimited comments such as

/* This is a delimited comment. It can be split over many lines */

can be spread over several lines. This type of comment begins with the delimiter /* and ends with the delimiter */. All text between the delimiters is ignored by the compiler. C# incorporated delimited comments and single-line comments from the C and C++ programming languages, respectively. In this book, we use only single-line comments in our programs.

Common Programming Error 3 1

Forgetting one of the delimiters of a delimited comment is a syntax error. The syntax of a programming language specifies the rules for creating a proper application in that language. A syntax error occurs when the compiler encounters code that violates C#'s language rules. In this case, the compiler does not produce an executable file. Instead, the compiler issues one or more error messages to help you identify and fix the incorrect code. Syntax errors are also called compiler errors, compile-time errors or compilation errors, because the compiler detects them during the compilation phase. You will be unable to execute your application until you correct all the syntax errors in it.

Line 2

// Text-printing application.

is a single-line comment that describes the purpose of the application.

Line 3

using System;

is a using directive that helps the compiler locate a class that is used in this application. A great strength of C# is its rich set of predefined classes that you can reuse rather than "reinventing the wheel." These classes are organized under namespacesnamed collections of related classes. Collectively, .NET's namespaces are referred to as the .NET Framework Class Library (FCL). Each using directive identifies predefined classes that a C# application should be able to use. The using directive in line 3 indicates that this example uses classes from the System namespace, which contains the predefined Console class (discussed shortly) used in Line 10, and many other useful classes.

Common Programming Error 3 2

All using directives must appear before any other code (except comments) in a C# source code file; otherwise a compilation error occurs.

Error Prevention Tip 3 1

Forgetting to include a using directive for a class used in your application typically results in a compilation error containing a message such as "The name 'Console' does not exist in the current context." When this occurs, check that you provided the proper using directives and that the names in the using directives are spelled correctly, including proper use of uppercase and lowercase letters.

For each new .NET class we use, we indicate the namespace in which it is located. This information is important because it helps you locate descriptions of each class in the .NET documentation. A Web-based version of this documentation can be found at

msdn2.microsoft.com/en-us/library/ms229335

This can also be found in the Visual C# Express documentation under the Help menu. You can also place the cursor on the name of any .NET class or method, then press the F1 key to get more information.

Line 4 is simply a blank line. Programmers use blank lines and space characters to make applications easier to read. Together, blank lines, space characters and tab characters are known as whitespace. (Space characters and tabs are known specifically as whitespace characters.) Whitespace is ignored by the compiler. In this and the next several chapters, we discuss conventions for using whitespace to enhance application readability.

Line 5

public class Welcome1

begins a class declaration for the class Welcome1. Every application consists of at least one class declaration that is defined by youthe programmer. These are known as user-defined classes. The class keyword introduces a class declaration and is immediately followed by the class name (Welcome1). Keywords (sometimes called reserved words) are reserved for use by C# and are always spelled with all lowercase letters. The complete list of C# keywords is shown in Fig. 3.2.

Figure 3.2. C# keywords.

C# Keywords

abstract

as

base

bool

break

byte

case

catch

char

checked

class

const

continue

decimal

default

delegate

do

double

else

enum

event

explicit

extern

false

finally

fixed

float

for

foreach

goto

if

implicit

in

int

interface

internal

is

lock

long

namespace

new

null

object

operator

out

override

params

private

protected

public

readonly

ref

return

sbyte

sealed

short

sizeof

stackalloc

static

string

struct

switch

this

throw

true

try

typeof

uint

ulong

unchecked

unsafe

ushort

using

virtual

void

volatile

while

     

By convention, all class names begin with a capital letter and capitalize the first letter of each word they include (e.g., SampleClassName). This is frequently referred to as Pascal casing. A class name is an identifiera series of characters consisting of letters, digits and underscores ( _ ) that does not begin with a digit and does not contain spaces. Some valid identifiers are Welcome1, identifier, _value and m_inputField1. 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. Normally, an identifier that does not begin with a capital letter is not the name of a class. C# is case sensitivethat is, uppercase and lowercase letters are distinct, so a1 and A1 are different (but both valid) identifiers. Identifiers may also be preceded by the @ character. This indicates that a word should be interpreted as an identifier, even if it is a keyword (e.g. @int). This allows C# code to use code written in other .NET languages where an identifier might have the same name as a C# keyword.

Good Programming Practice 3 1

By convention, always begin a class name's identifier with a capital letter and start each subsequent word in the identifier with a capital letter.

Common Programming Error 3 3

C# is case sensitive. Not using the proper uppercase and lowercase letters for an identifier normally causes a compilation error.

In Chapters 38, every class we define begins with the keyword public. For now, we will simply require this keyword. You will learn more about public and non-public classes in Chapter 9. When you save your public class declaration in a file, the file name is usually the class name followed by the .cs filename extension. For our application, the file name is Welcome1.cs.

Good Programming Practice 3 2

By convention, a file that contains a single public class should have a name that is identical to the class name (plus the .cs extension) in terms of both spelling and capitalization. Naming your files in this way makes it easier for other programmers (and you) to determine where the classes of an application are located.

A left brace (in line 6 in Fig. 3.1), {, begins the body of every class declaration. A corresponding right brace (in line 12), }, must end each class declaration. Note that lines 711 are indented. This indentation is one of the spacing conventions mentioned earlier. We define each spacing convention as a Good Programming Practice.

Error Prevention Tip 3 2

Whenever you type an opening left brace, {, in your application, immediately type the closing right brace, }, then reposition the cursor between the braces and indent to begin typing the body. This practice helps prevent errors due to missing braces.

Good Programming Practice 3 3

Indent the entire body of each class declaration one "level" of indentation between the left and right braces that delimit the body of the class. This format emphasizes the class declaration's structure and makes it easier to read. You can let the IDE format your code by selecting Edit > Advanced > Format Document.

Good Programming Practice 3 4

Set a convention for the indent size you prefer, then uniformly apply that convention. The Tab key may be used to create indents, but tab stops vary among text editors. We recommend using three spaces to form each level of indentation. We show how to do this in Section 3.3.

Common Programming Error 3 4

It is a syntax error if braces do not occur in matching pairs.

Line 7

// Main method begins execution of C# application

is a comment indicating the purpose of lines 811 of the application. Line 8

public static void Main( string[] args )

is the starting point of every application. The parentheses after the identifier Main indicate that it is an application building block called a method. Class declarations normally contain one or more methods. Method names usually follow the same Pascal casing capitalization conventions used for class names. For each application, exactly one of the methods in a class must be called Main (which is typically defined as shown in line 8); otherwise, the application will not execute. Methods are able to perform tasks and return information when they complete their tasks. Keyword void (line 8) indicates that this method will not return any information after it completes its task. Later, we will see that many methods do return information. You will learn more about methods in Chapters 4 and 7. For now, simply mimic Main's first line in your applications.

The left brace in line 9 begins the body of the method declaration. A corresponding right brace must end the method's body (line 11 of Fig. 3.1). Note that line 10 in the body of the method is indented between the braces.

Good Programming Practice 3 5

As with class declarations, indent the entire body of each method declaration one "level" of indentation between the left and right braces that define the method body. This format makes the structure of the method stand out and makes the method declaration easier to read.

Line 10

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

instructs the computer to perform an actionnamely, to print (i.e., display on the screen) the string of characters contained between the double quotation marks. A string is sometimes called a character string, a message or a string literal. We refer to characters between double quotation marks simply as strings. Whitespace characters in strings are not ignored by the compiler.

Class Console provides standard input/output capabilities that enable applications to read and display text in the console window from which the application executes. The Console.WriteLine method displays (or prints) a line of text in the console window. The string in the parentheses in line 10 is the argument to the method. Method Console.WriteLine performs its task by displaying (also called outputting) its argument in the console window. When Console.WriteLine completes its task, it positions the screen cursor (the blinking symbol indicating where the next character will be displayed) at the beginning of the next line in the console window. (This movement of the cursor is similar to what happens when a user presses the Enter key while typing in a text editorthe cursor moves to the beginning of the next line in the file.)

The entire line 10, including Console.WriteLine, the parentheses, the argument "Welcome to C# Programming!" in the parentheses and the semicolon (;), is called a statement. Each statement ends with a semicolon. When the statement in line 10 executes, it displays the message Welcome to C# Programming! in the console window. A method is typically composed of one or more statements that perform the method's task.

Common Programming Error 3 5

Omitting the semicolon at the end of a statement is a syntax error.

Error Prevention Tip 3 3

When learning how to program, sometimes it is helpful to "break" a working application so you can familiarize yourself with the compiler's syntax-error messages. Try removing a semicolon or brace from the code of Fig. 3.1, then recompiling the application to see the error messages generated by the omission.

Error Prevention Tip 3 4

When the compiler reports a syntax error, the error may not be in the line indicated by the error message. First, check the line for which the error was reported. If that line does not contain syntax errors, check several preceding lines.

Some programmers find it difficult when reading or writing an application to match the left and right braces ({ and }) that delimit the body of a class declaration or a method declaration. For this reason, some programmers include a comment after each closing right brace (}) that ends a method declaration and after each closing right brace that ends a class declaration. For example, line 11

} // end method Main

specifies the closing right brace of method Main, and line 12

} // end class Welcome1

specifies the closing right brace of class Welcome1. Each of these comments indicates the method or class that the right brace terminates. Visual Studio can help you locate matching braces in your code. Simply place the cursor next to one brace and Visual Studio will highlight the other.

Good Programming Practice 3 6

Following the closing right brace of a method body or class declaration with a comment indicating the method or class declaration to which the brace belongs improves application readability.

Creating Your Simple Application in Visual C# Express

Категории