Statements

In C# a complete program instruction is called a statement . Programs consist of sequences of C# statements. Each statement must end 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 bottom. This would be entirely straightforward, and terribly limiting, were it not for branching. There are two types of branches in a C# program: unconditional branching and conditional branching.

Program flow is also affected by looping and iteration statements, which are signaled by the keywords for, while, do, in, and foreach. Iteration is discussed later in this chapter. For now, let’s consider some of the more basic methods of conditional and unconditional branching.

Unconditional Branching Statements

An unconditional branch is created 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; class Functions { static void Main( ) { Console.WriteLine("In Main! Calling SomeMethod( )..."); SomeMethod( ); Console.WriteLine("Back in Main( )."); } static void SomeMethod( ) { Console.WriteLine("Greetings ...

Get Programming C#, Third 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.