Branching and Looping in C#, Part 1
(Page 1 of 6 )
Certainly you are familiar with if, switch, while, return and goto statements. These are famous Branching and Looping statements in many programming languages for selecting code paths conditionally, looping and jumping to another part of your application unconditionally. In this article we will discuss what C# offers to us from these statements. As you will see, the common programming errors that existed in C++ were eliminated with C# statements.
The if Statement
The if statement gives you the ability to test an expression, then select a statement or a group of statements to be executed if the expression evaluates to true. If you have the else part of the statement, you can execute another statement (or statements) if the expression evaluates to false. The syntax of if statement is as follows:
if(bool expression)
statement 1;
As we will see shortly, the expression must evaluate to bool value (true or false). If you have more than one statement, you must put the statements in a block using curly braces:
if(bool expression)
{
statement 1;
statement 2;
statement 3;
}
The same applies to the else statement, so if you have only one statement to execute with the else statement, you can write it like this:
if(bool expression)
statement 1;
else
statement 1;
But if you have multiple statements in your else part, you can write it as:
if(bool expression)
{
statement 1;
statement 2;
statement 3;
}
else
{
statement 1;
statement 2;
statement 3;
}
For consistency, use the curly braces even if you have only one statement with the if statement or with the else statement. Most programmers prefer this usage.
Next: No Implicit Conversion >>
More C# Articles
More By Michael Youssef