C # Fundamentals of Process Control statements

Source: Internet
Author: User
Tags case statement finally block terminates

C # programs execute on a line-by-line, top-down, with no missing code. In order for the program to execute according to the process designed by the developer, it is necessary to make the process of condition judgment, loop and jump, which need to realize the process control. The Process Control in C # contains four aspects of conditional statements, loop statements, jump statements, and exception handling.
One, jump statement
Break statement: Terminates and jumps out of the loop body.

Continue statement: Terminates the current loop and restarts a new loop.

Goto statement: Jumps to the specified position.
C # allows you to tag lines of code so that you can jump directly to them using a goto statement. The Goto statement uses the following:
goto<labelname>;
The label is defined in the following way:
<labelname>:
The goto statement has two restrictions, cannot jump to a code block such as a for loop, and cannot jump out of the scope of a class, and cannot exit the finally block after the Try...catch statement.
The goto statement is explained here only to understand its syntax, when encountered can know the meaning of the code, I do not recommend to use.

Return statement: Jumps out of the loop and the functions it contains.

Throw statement: Throws an exception.

second, conditional statement
Conditional statements can control the execution branch of the code depending on whether the condition satisfies or is based on the value of the expression. C # has two structures that control the branch of the control code, namely the IF statement and the switch statement.
if statement
Note: The condition of the IF statement can be a Boolean variable or an expression, but if it is an expression, The result of an expression must be a Boolean value.
1, single-Select if statement, that is, conditional execution, the syntax is as follows:
if (condition)
{
    do;
}

2, IfElse statement, that is, conditional execution A or execute B, the syntax is as follows:
if (condition)
{
    do A;
}
Else
{
    do B;
}
Extended: Ternary operator?: is also equivalent to a ifelse statement, the syntax is as follows:< expression >? <resultIfTrue> : <resultIfFalse>  Where the evaluated expression can get a Boolean value, the result of the
operator determines whether it is <resultiftrue>, or <resultIfFalse>. Example:

            int 8 ;             string Ten " less than ten " " Greater than ten ";

3, multi-Select if statement, that is, to judge multiple conditions, the implementation of the establishment, the syntax is as follows:
if (condition 1)
{
Do A;
}
else if (condition 2)
{
Do B;
}
else if (condition 3)
{
Do C;
}
Else
{
Do D;
}
There is no limit to the number of else if statements, but if the else if statement is large, you should consider another branching structure: the switch statement.
Note: The multi-Select if statement is top-down and will not judge any other condition if one condition is established.

Switch Statement
The Switch...case statement is suitable for selecting an execution branch from a set of mutually exclusive branches. It is in the form of a switch parameter followed by a set of case clauses. If the value of the expression in the switch parameter equals a value next to a case clause, the code in the case clause is executed. You do not need to use curly braces to group statements into blocks, just use the break statement to mark the end of each case code. You can also include a default clause in a switch statement that executes the code of the default clause if the expression is not equal to the value of any case clause. Its syntax is as follows:
switch (expression)
{
Case 1:
Console.WriteLine ("1");
Break
Case 2:
Console.WriteLine ("2");
Break
Case 3:
Console.WriteLine ("3");
Break
Default
Console.WriteLine ("4");
Break
}
Note: The value after each case statement of the switch statement must be the same as the type of the value that is obtained by the expression, must be a constant, cannot be a variable, and the value after all case statements in a switch statement must be mutually exclusive, meaning that the value following the case cannot have two identical values. Because the values behind all case statements must be mutually exclusive, the order of discharge for the case statement is irrelevant, and even the default statement can be placed at the front! But to develop good programming habits and code there is clear logic, I do not recommend this writing; The default statement in a switch statement can only exist one, cannot exist more than one; Usually, there must be a break statement behind each case. The break statement interrupts the execution of the switch statement, but other interrupt statements can be used in C # to interrupt the switch statement, such as a return statement, a goto statement. There is a difference between using the break statement and the return statement, break statement only interrupts the execution of the switch statement, if there are other code behind the switch statement can continue to execute, but the return statement break will break the switch statement method, That is, the code behind the switch statement will not execute, and the method where the switch statement is located will be returned directly. You can use a goto statement to jump from one case to another, as in the following code:

            intA =1; Switch(a) { Case 1: Console.WriteLine ("1"); Goto  Case 2;  Case 2: Console.WriteLine ("2");  Break;  Case 3: Console.WriteLine ("3");  Break; default: Console.WriteLine ("4");  Break; }

Program Description: Case 2 is executed directly after the program executes case 1. However, we do not recommend this, which leads to hard-to-detect logic errors.

Normally, when a case statement is processed in a switch statement, it is not free to enter the next case statement, but there is one exception to this rule. If you put multiple case statements together, followed by a block of code, you actually check multiple conditions at once, and if any of those conditions are met, the code executes, for example:

            intA =2; Switch(a) { Case 1:                                          Case 2:                                               Case 3: Console.WriteLine ("1 or 2 or 3 .");  Break; default: Console.WriteLine ("4");  Break; }

third, the circular statement
Loop is repeated execution of the statement, the loop structure can implement a program module of repeated execution, it is to simplify our programs, better organization algorithm has important significance.
1. Do Loop
The structure of the Do loop is as follows:
Do
{
Statement or statement block;
}while (expression);
The Do loop executes the statement or statement block before judging the value of the expression, and if the value of the expression is true, the loop continues until the value of the expression is false. Note: When the Do loop is executed, the value of the expression is executed once, regardless of whether the expression is true or false, before it is evaluated. That is, if the first expression has a value of false, it also executes a loop. Do loop the statement or statement block executes at least once, regardless of whether the Boolean expression is true or false. In addition, a semicolon (;) must be used after the while statement.

2. While loop
The structure of the while loop is as follows:
while (expression)
{
Statement or statement block;
}
The while loop evaluates the value of the expression before executing the statement or block of statements until the value of the expression is false. If the value of the loop-first expression is false, then the statement or statement block is not executed.

3. For loop
The structure of the For loop is as follows:
For (< initialization expressions >;< conditional expressions >;< iterator for delta >)
{
Statement or statement block;
}
Initialization expression: You can define a variable at that location and assign it a starting value, or you can use the variable defined earlier for the For loop, but the variable defined earlier with the For loop must be assigned a starting value at that location. Note: Define a variable at that location and assign it a starting value, the scope of the variable defined by this usage is only in the FOR Loop statement, which means that the code behind the FOR Loop statement cannot use the variable But the code that follows the usage definition of a variable defined by a For loop can also use the variable for a loop statement.
Conditional expression: It is the condition that the loop continues or terminates.
Iterate represents the type: After executing the statement or statement block, the iterator is executed, and then the conditional expression is executed to determine whether the loop continues.
For loop Example:

            // Print 1 to 10 on            the screen  for (int a =1; a++)            {                Console.WriteLine (a);            }                        Console.readkey ();

4. Foreach Loop
The foreach statement is used to enumerate the elements of a collection and to execute an embedded statement once for each element in the collection. The structure of the Foreach loop is as follows:
foreach (< type > < iterate variable name > in < set >)
{
Statement or statement block;
}
Note: The type of the iteration variable must be the same as the type of the collection. The number of elements in the set determines the number of times the program segment repeats in the loop, and each time it enters a loop, it assigns the contents of the collection element to the variable, and then jumps out of the Foreach loop when all the elements have been read. The Foreach Loop has read-only access to elements within the collection and cannot change the value of any element. The Foreach loop cannot add elements to the collection or delete elements during a loop. Example:

            list<stringnew list<string>();              for (int a =1; a++)            {                Strlist.add (a.tostring ());            }             foreach (string in strlist)            {                Console.WriteLine (str);                Strlist.remove (str);            }            Console.readkey ();

The foreach statement in the above program produces an exception when the first element in the output collection Strlist and removes the collection for the next loop.

5. Infinite loop
When code is written incorrectly or deliberately designed, you can define a loop that never terminates, the so-called Infinite loop. Example:
while (true)
{
Statement or statement block;
}
An infinite loop statement is also useful, and you can use the break statement or manually exit the infinite loop using the Windows Task Manager.

Iv. Exception Handling
Exception handling in C # is also a process control, try...catch...finally statements for exception capture and processing, with the following syntax:
Try
{
Statement or statement block;
}
catch (<execptionType> e)
{
Statement or statement block;
}
Finally
{
Statement or statement block;
}
Try: Contains the code that throws the exception.
Catch: Contains the code to execute when an exception is thrown. Catch blocks can be set with <execptionType> to respond only to specific exception types to provide multiple catch blocks.
Finally: Contains code that is always executed, and if no exception is generated, executes after the try block and, if an exception is handled, executes after the catch block.
The order in which the try...catch...finally statements are executed is:
1. The try block interrupts the execution of the program at the place where the exception occurred.
2. If there is a catch block, check that the block matches the thrown exception type. If there is no catch block, the finally block is executed (if there is no catch block, there must be a finally block).
3. If there is a catch block, but it does not match the exception type that has occurred, check for additional catch blocks.
4. If there is a catch block that matches the exception type that has occurred, execute the code it contains, and then execute the finally block (if any).
5. If the catch block does not match the exception type that has occurred, then the finally block, if any, is executed.
From the execution order of try...catch...finally statements, we can see that there are many combinations of try...catch...finally statements, which are not explained in detail here.

C # Fundamentals of Process Control statements

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.