Share via


Statements (C# Programming Guide)

The actions that a program takes are expressed in statements. Common actions include declaring variables, assigning values, calling methods, looping through collections, and branching to one or another block of code, depending on a given condition. The order in which statements are executed in a program is called the flow of control or flow of execution. The flow of control may vary every time that a program is run, depending on how the program reacts to input that it receives at run time.

A statement can consist of a single line of code that ends in a semicolon, or a series of single-line statements in a block. A statement block is enclosed in {} brackets and can contain nested blocks. The following code shows two examples of single-line statements, and a multi-line statement block:

static void Main() 
    {
        // Declaration statement. 
        int counter;

        // Assignment statement.
        counter = 1;

        // Error! This is an expression, not an expression statement. 
        // counter + 1;  

        // Declaration statements with initializers are functionally 
        // equivalent to a declaration statement followed by assignment statement:          
        int[] radii = { 15, 32, 108, 74, 9 }; // Declare and initialize an array. 
        const double pi = 3.14159; // Declare and initialize a constant.           

        // foreach statement block that contains multiple statements. 
        foreach (int radius in radii)
        {
            // Declaration statement with initializer. 
            double circumference = pi * (2 * radius);

            // Expression statement (method invocation). A single-line 
            // statement can span multiple text lines because line breaks 
            // are treated as white space, which is ignored by the compiler.
            System.Console.WriteLine("Radius of circle #{0} is {1}. Circumference = {2:N2}",
                                    counter, radius, circumference);

            // Expression statement (postfix increment).
            counter++;

        } // End of foreach statement block
    } // End of Main method body.
} // End of SimpleStatements class. 
/*
   Output:
    Radius of circle #1 = 15. Circumference = 94.25
    Radius of circle #2 = 32. Circumference = 201.06
    Radius of circle #3 = 108. Circumference = 678.58
    Radius of circle #4 = 74. Circumference = 464.96
    Radius of circle #5 = 9. Circumference = 56.55
*/

Types of Statements

The following table lists the various types of statements in C# and their associated keywords, with links to topics that include more information:

Category

C# keywords / notes

Declaration statements

A declaration statement introduces a new variable or constant. A variable declaration can optionally assign a value to the variable. In a constant declaration, the assignment is required.

Expression statements

Expression statements that calculate a value must store the value in a variable.

Selection statements

Selection statements enable you to branch to different sections of code, depending on one or more specified conditions. For more information, see the following topics:

if, else, switch, case

Iteration statements

Iteration statements enable you to loop through collections like arrays, or perform the same set of statements repeatedly until a specified condition is met. For more information, see the following topics:

do, for, foreach, in, while

Jump statements

Jump statements transfer control to another section of code. For more information, see the following topics:

break, continue, default, goto, return, yield

Exception handling statements

Exception handling statements enable you to gracefully recover from exceptional conditions that occur at run time. For more information, see the following topics:

throw, try-catch, try-finally, try-catch-finally

Checked and unchecked

Checked and unchecked statements enable you to specify whether numerical operations are allowed to cause an overflow when the result is stored in a variable that is too small to hold the resulting value. For more information, see checked and unchecked.

The fixed statement

The fixed statement prevents the garbage collector from relocating a movable variable. For more information, see fixed.

The lock statement

The lock statement enables you to limit access to blocks of code to only one thread at a time. For more information, see lock.

Labeled statements

You can give a statement a label and then use the goto keyword to jump to the labeled statement. (See the example in the following row.)

The empty statement

The empty statement consists of a single semicolon. It does nothing and can be used in places where a statement is required but no action needs to be performed. The following examples show two uses for an empty statement:

Embedded Statements

Some statements, including do, while, for, and foreach, always have an embedded statement that follows them. This embedded statement may be either a single statement or multiple statements enclosed by {} brackets in a statement block. Even single-line embedded statements can be enclosed in {} brackets, as shown in the following example:

// Recommended style. Embedded statement in a block. 
foreach (string s in System.IO.Directory.GetDirectories(
                        System.Environment.CurrentDirectory))
{
    System.Console.WriteLine(s);
}

// Not recommended. 
foreach (string s in System.IO.Directory.GetDirectories(
                        System.Environment.CurrentDirectory))
    System.Console.WriteLine(s);

An embedded statement that is not enclosed in {} brackets cannot be a declaration statement or a labeled statement. This is shown in the following example:

if(pointB == true)
    //Error CS1023: 
    int radius = 5; 

Put the embedded statement in a block to fix the error:

if(b == true)
{
    // OK:
    System.DateTime d = System.DateTime.Now;
    System.Console.WriteLine(d.ToLongDateString());
}

Nested Statement Blocks

Statement blocks can be nested, as shown in the following code:

foreach (string s in System.IO.Directory.GetDirectories(
    System.Environment.CurrentDirectory))
{
    if (s.StartsWith("CSharp"))
    {
        if (s.EndsWith("TempFolder"))
        {
            return s;
        }
    }

}
return "Not found.";

Unreachable Statements

If the compiler determines that the flow of control can never reach a particular statement under any circumstances, it will produce warning CS0162, as shown in the following example:

// An over-simplified example of unreachable code. 
const int val = 5;
if (val < 4)
{
    System.Console.WriteLine("I'll never write anything."); //CS0162
}

C# Language Specification

For more information, see the following sections in the C# Language Specification:

  • 1.5 Statements

  • 8 Statements

See Also

Concepts

C# Programming Guide

Change History

Date

History

Reason

July 2008

Added new code examples and table, and revised the text.

Information enhancement.