Information Technology Reference
In-Depth Information
Statements
The statements in C# are very similar to those of C and C++. This section will introduce the gen-
eral form of statements; the specific statement forms will be covered in Chapter 9.
Simple Statements
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 state-
ment defines a variable named
var1
and initializes its value to
5
. The second statement prints
the value of variable
var1
to the screen.
int var1 = 5;
System.Console.WriteLine("The value of var1 is {0}", var1);
Blocks
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 enclos-
ing 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.)
{
↓
Terminating semicolon
Terminating semicolon
int var2 = 5;
↓
System.Console.WriteLine("The value of var1 is {0}", var1);
}
↑
No terminating semicolon