This chapter will lay the groundwork for studying C#. Since I will use code samples extensively throughout the text, I first need to show you what a C# program looks like and what its various parts mean.
I'll start by demonstrating a simple program and explaining its components one by one. This will introduce a range of topics, from the structure of a C# program to the method of producing program output to the screen.
With these source code preliminaries under your belt, I can then use code samples freely throughout the rest of the text. So, unlike the following chapters, where one or two topics will be covered in detail, this chapter will touch on many topics with only a minimum of explanation.
Let's start by looking at a simple C# program. The complete program source is shown in the top shaded area in Figure 2-1. As shown, the code is contained in a text file called SimpleProgram.cs
. As you read through it, don't worry about understanding all the details. Table 2-1 gives a line-by-line description of the code.
When the code is compiled and executed, it displays the string "Hi there!" in a window on the screen.
One line contains two contiguous slash characters. These characters—and everything following them on the line—are ignored by the compiler. This is called a single-line comment.
Table 2-1. The SimpleProgram Program, Line by Line
Line Number | Description |
---|---|
Line 1 | Tells the compiler that this program uses types from the |
Line 3 | Declares a new namespace, called
|
Line 5 | Declares a new class type, called
|
Line 7 | Declares a method called
|
Line 9 | Contains only a single, simple statement; this line constitutes the body of
|
A C# program consists of one or more type declarations. Much of this book is spent explaining the different types that you can create and use in your programs. The types in a program can be declared in any order. In the SimpleProgram
example, only the class
type is declared.
A namespace is aset of type declarations associated with a name. SimpleProgram
uses two namespaces. It creates a new namespace called Simple
, and uses a predefined namespace called System
.
To compile the program, you can use Visual Studio or the command-line compiler. To use the command-line compiler, in its simplest form, use the following command:
csc SimpleProgram.cs
In this command, csc
is the name of the command-line compiler and SimpleProgram.cs
is the name of the source file.
Identifiers are character strings used to name things such as variables, methods, parameters, and a host of other programming constructs that will be covered later.
You can create self-documenting identifiers by concatenating meaningful words into a single descriptive name, using uppercase and lowercase letters (e.g., CardDeck, PlayersHand, FirstName, SocSecurityNum
). Certain characters are allowed or disallowed at certain positions in an identifier. These rules are illustrated in Figure 2-2.
The alphabetic and underscore characters (a
through z, A
through Z
, and _
) are allowed at any position.
Digits are not allowed in the first position, but are allowed everywhere else.
The @
character is allowed in the first position of an identifier, but not anywhere else. The use of the @
character, although allowed, is discouraged for general use.
Identifiers are case sensitive. For instance, the variable names myVar
and MyVar
are different identifiers. It is generally a bad idea, however, to have identifiers that differ only in the case of some of the letters.
As an example, in the following code snippet, the variable declarations are all valid and declare different integer variables. But using such similar names will make coding more error-prone and debugging more difficult. Those debugging your code at some later time will not be pleased.
// Valid syntactically, but don't do this! int totalCycleCount; int TotalCycleCount; int TotalcycleCount;
The C# Language Specification suggests that certain casing conventions be used in creating identifiers. The suggested guidelines for casing are described and summarized in Table 2-2.
For most identifiers, the Pascal casing style should be used. In this style, each of the words combined to make an identifier is capitalized—for example, FirstName
and LastName
.
Table 2-2. Recommended Identifier Naming Styles
Style Name | Description | Recommended Use | Examples |
---|---|---|---|
Pascal casing | Each word in the identifier is capitalized. | Use for type names and member names. |
|
Each word in the identifier, except the first, is capitalized. | Use for local variables and method parameters. |
| |
Uppercase | The identifier is composed of all uppercase letters. | Use only for abbreviations. |
|
Although these are the suggested guidelines, many organizations use other conventions—particularly in the naming of member fields, which will be introduced in the next chapter. Two of the common conventions are the following:
Begin a field name with an underscore: _HighTemp, _LowTemp
.
Begin a field name with m_
: m_HighTemp, m_LowTemp
.
Both of these methods have the advantage of showing you immediately that these identifiers are field names. These forms also allow Visual Studio's IntelliSense feature to group all the fields together in the pop-ups.
Keywords are the character string tokens used to define the C# language. A complete list of the C# keywords is given in Table 2-3.
Some important things to know about keywords are the following:
Table 2-3. The C# Keywords
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Contextual keywords are identifiers that act as keywords only in certain language constructs. In those positions, they have particular meanings; but unlike keywords, which cannot ever be used as identifiers, contextual keywords can be used as identifiers in other parts of the code. The list of contextual keywords is shown in Table 2-4.
Every C# program must have one class with a method (function) called Main
. In the SimpleProgram
program shown previously, it was declared in a class called Program
.
The starting point of execution of every C# program is at the first instruction in Main
.
The name Main
must be capitalized.
The simplest form of Main
is the following:
static void Main( )
{
Statements
}
Whitespace in a program refers to characters that do not have a visible output character. Whitespace in source code is ignored by the compiler, but is used by the programmer to make the code clearer and easier to read. Some of the whitespace characters include the following:
Space
Tab
New line
Carriage return
For example, the following code fragments are treated exactly the same by the compiler in spite of their differences in appearance.
// Nicely formatted Main() { Console.WriteLine("Hi, there!"); } // Just concatenated Main(){Console.WriteLine("Hi, there!");}
The statements in C# are very similar to those of C and C++. This section will introduce the general form of statements; the specific statement forms will be covered in Chapter 9.
A statement is a source code instruction describing a type or telling the program to perform an action.
A simple statement is terminated by a semicolon.
For example, the following code is a sequence of two simple statements. The first statement defines a variable named var1
and initializes its value to 5
. The second statement prints the value of variable var1
to a window on the screen.
int var1 = 5; System.Console.WriteLine("The value of var1 is {0}", var1);
A block is a sequence of zero or more statements enclosed by a matching set of curly braces; it acts as a single syntactic statement.
You can create a block from the set of two statements in the preceding example by enclosing the statements in matching curly braces, as shown in the following code:
{ int var1 = 5; System.Console.WriteLine("The value of var1 is {0}", var1); }
Some important things to know about blocks are the following:
You can use a block whenever the syntax requires a statement but the action you need requires more than one simple statement.
Certain program constructs require blocks. In these constructs, you cannot substitute a simple statement for the block.
Although a simple statement is terminated by a semicolon, a block is not followed by a semicolon. (Actually, the compiler will allow it—but it's not good style.)
A console window is a simple command prompt window that allows a program to display text and receive input from the keyboard. The BCL supplies a class called Console
(in the System
namespace), which contains methods for inputting and outputting data to a console window.
Write
is a member of the Console
class. It sends a text string to the program's console window. In its simplest form, Write
sends a literal string of text to the window. The string must be enclosed in quotation marks.
The following line of code shows an example of using the Write
member:
This code produces the following output in the console window:
This is trivial text.
Another example is the following code, which sends three literal strings to the program's console window:
System.Console.Write ("This is text1."); System.Console.Write ("This is text2."); System.Console.Write ("This is text3.");
This code produces the output that follows. Notice that Write
does not append a newline character after the string, so the output of the three statements runs together on a single line.
WriteLine
is another member of Console
, which performs the same functions as Write
, but appends a newline character to the end of each output string.
For example, if you use the preceding code, substituting WriteLine
for Write
, the output is on separate lines:
System.Console.WriteLine("This is text 1."); System.Console.WriteLine("This is text 2."); System.Console.WriteLine("This is text 3.");
This code produces the following output in the console window:
This is text 1. This is text 2. This is text 3.
The general form of the Write
and WriteLine
statements takes more than a single parameter.
If there is more than a single parameter, the parameters are separated by commas.
The first parameter must always be a string, and is called the format string.
The format string can contain substitution markers. A substitution marker marks the position in the format string where a value should be substituted in the output string. It consists of an integer enclosed in a set of matching curly braces. The integer is the numeric position of the substitution value to be used.
The parameters following the format string are called substitution values. These substitution values are numbered, starting at 0.
The syntax is as follows:
Console.WriteLine(FormatString
,SubVal0
,SubVal1
,SubVal2
, ...);
For example, the following statement has two substitution markers, numbered 0
and 1
, and two substitution values, whose values are 3
and 6
, respectively.
This code produces the following output on the screen:
Two sample integers are 3 and 6.
In C#, you can use any number of markers and any number of values.
The values can be used in any order.
The values can be substituted any number of times in the format string.
For example, the following statement uses three markers and only two values. Notic8e that value 1
is used before value 0
, and that value 1
is used twice.
Console.WriteLine("Three integers are {1}, {0} and {1}.", 3, 6);
This code displays the following on the screen:
Three integers are 6, 3 and 6.
A marker must not attempt to reference a value at a position beyond the length of the list of substitution values. If it does, it will not produce a compile error but a runtime error (called an exception).
For example, in the following statement there are two substitution values, with positions 0
and 1
. The second marker, however, references position 2
—which does not exist. This will produce a runtime error.
You have already seen single-line comments, so here I'll discuss the second type of inline comments—delimited comments—and mention a third type called documentation comments.
Delimited comments have a start marker and an end marker.
Text between the matching markers is ignored by the compiler.
Delimited comments can span any number of lines.
For example, the following code shows a delimited comment spanning multiple lines.
A delimited comment can also span just part of a line. For example, the following statement shows text commented out of the middle of a line. The result is the declaration of a single variable, var2
.
Single-line and delimited comments behave in C# just as they do in C and C++.
There are several other important things you need to know about comments:
Nested comments are not allowed. Only one comment can be in effect at a time.
The comment that starts first is in effect until the end of its scope. The scope for particularly comment types is as follows:
For single-line comments, the end of the current line
For delimited comments, the first end delimiter encountered
The following attempts at comments are incorrect:
C# also provides a third type of comment: the documentation comment. Documentation comments contain XML text that can be used to produce program documentation. Comments of this type look like single-line comments, except that they have three contiguous slashes rather than two. I will cover documentation comments in Chapter 25.
The following code shows the form of documentation comments:
/// <summary> /// This class does... /// </summary> class Program { ...
Inline comments are sections of text that are ignored by the compiler but are included in the code to document it. Programmers insert comments into their code to explain and document it. Table 2-5 gives a summary of the comment types.
Table 2-5. Comment Types
Type | Start | End | Description |
---|---|---|---|
Single-line |
| The text from the beginning marker to the end of the current line is ignored by the compiler. | |
Delimited |
|
| The text between the start and end markers is ignored by the compiler. |
Documentation |
| Comments of this type contain XML text that is meant to be used by a tool to produce program documentation. |
3.135.200.14