Main: The Starting Point of a Program
This chapter lays the groundwork for studying C#. Since I'll 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 out of the way, I can then use code samples freely throughout the rest of the text. So, unlike the following chapters, where one or two topics are covered in detail, this chapter touches 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.
Figure 2-1. The SimpleProgram program
Table 2-1. The SimpleProgram Program, Line by Line
Line Number | Description |
Line 1 | Tells the compiler that this program uses types from the System namespace. |
Line 3 | Declares a new namespace, called Simple .
|
Line 5 | Declares a new class type, called Program .
|
Line 7 | Declares a method called Main as a member of class Program .
|
Line 9 | Contains only a single, simple statement; this line constitutes the body of Main .
|
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 a class
type is declared.
A namespace is a set of type declarations associated with a name. SimpleProgram
uses two namespaces. It creates a new namespace called Simple
, in which it declares its type (class Program
), and uses the Console
class defined in a 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 in a command window:
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
, SocialSecurityNum
). Certain characters are allowed or disallowed at certain positions in an identifier. Figure 2-2 illustrates these rules.
a
through z
, A
through Z
, and _
) are allowed at any position.@
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.Figure 2-2. Characters allowed in identifiers
Identifiers are case-sensitive. For instance, the variable names myVar
and MyVar
are different identifiers. It's generally a bad idea, however, to have identifiers that differ only in the case of some of the letters, because they're easily confused.
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. Table 2-2 summarizes the suggested guidelines for casing.
For most type identifiers, the Pascal casing style is recommended. 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. | CardDeck, DealersHand |
Camel casing | Each word in the identifier, except the first, is capitalized. | Use for local variables and method parameters. | totalCycleCount, randomSeedParam |
Uppercase | The identifier is composed of all uppercase letters. | Use only for abbreviations. | IO, DMA, XML |
Although these are the suggested guidelines, many organizations use other conventions—particularly in the naming of member fields, which I'll introduce in the next chapter. Two of the common conventions are the following:
_highTemp
, _lowTemp
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. Table 2-3 gives a complete list of the C# keywords.
Some important things to know about keywords are the following:
@
character.abstract |
const |
extern |
int |
out |
short |
typeof |
as |
continue |
false |
interface |
override |
sizeof |
uint |
base |
decimal |
finally |
internal |
params |
stackalloc |
ulong |
bool |
default |
fixed |
is |
private |
static |
unchecked |
break |
delegate |
float |
lock |
protected |
string |
unsafe |
Byte |
do |
for |
long |
public |
struct |
ushort |
case |
double |
foreach |
namespace |
readonly |
switch |
using |
catch |
else |
goto |
new |
ref |
this |
virtual |
char |
enum |
if |
null |
return |
throw |
void |
checked |
event |
implicit |
object |
sbyte |
true |
volatile |
class |
explicit |
in |
operator |
sealed |
try |
while |
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. Table 2-4 contains the list of contextual keywords.
Table 2-4. The C# Contextual Keywords
add |
ascending |
by |
descending |
dynamic |
equals |
from |
get |
global |
group |
into |
join |
let |
on |
orderby |
partial |
remove |
select |
set |
value |
var |
where |
yield |
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
.
Main
.Main
must be capitalized.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:
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 introduces the general form of statements; the specific statement forms are covered in Chapter 9.
A statement is a source code instruction describing a type or telling the program to perform an action.
For example, the following code is a sequence of two simple statements. The first statement defines an integer 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:
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—double quotes, not single quotes.
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 a 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.
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.
For example, the following statement uses three markers and only two values. Notice 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've 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.
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
.
Note Single-line and delimited comments behave in C# just like they do in C and C++.
There are several other important things you need to know about comments:
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'll 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 summarizes the 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. |
18.118.31.67