Statements
In C#, a complete program instruction is called a statement. Programs consist of sequences of C# statements. Virtually every statement ends with a semicolon (;
). For example:
int x; // a statement x = 23; // another statement int y = x; // yet another statement
C# statements are evaluated in order. The compiler starts at the beginning of a statement list and makes its way to the end. This would be entirely straightforward, and terribly limiting, were it not for branching. There are two types of branches in a C# program: unconditional branches and conditional branches.
Program flow is also affected by looping and iteration statements, which are signaled by the keywords for, while, do, in
, and foreach
. I discuss iteration later in this chapter. For now, let's consider some of the more basic methods of conditional and unconditional branching.
Unconditional Branching Statements
You can create an unconditional branch in one of two ways. The first way is by invoking a method. When the compiler encounters the name of a method, it stops execution in the current method and branches to the newly "called" method. When that method returns a value, execution picks up in the original method on the line just below the method call. Example 3-6 illustrates.
Example 3-6. Calling a method
using System; namespace CallingAMethod { class CallingAMethod { static void Main( ) { Console.WriteLine("In Main! Calling SomeMethod( )..."); SomeMethod( ); Console.WriteLine("Back in Main( )."); } static void ...
Get Programming C# 3.0, 5th Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.