C# if...else Statement
A if statement An if statement can be followed by an optional else statement, which executes when the Boolean expression is false.
Syntax
In C#, if...else statement syntax:
if(boolean_expression)
{
/* statement to execute if the boolean expression is true */
}
else
{
/* statement to execute if the boolean expression is false */
}
If the Boolean expression is true, then the if block's code is executed. If the Boolean expression is false, then the else block's code.
Flowchart
Example
Example
using
System
;
namespace
DecisionMaking
{
class
Program
{
static
void
Main
(
string
[
]
args
)
{
/* Local variable definition */
int
a
=
100
;
/* Check the Boolean condition */
if
(
a
<
20
)
{/* If the condition is true, output the following statement */
Console
.
WriteLine
(
"a is less than 20"
)
;
}
else
{
/* If the condition is false, output the following statement */
Console
.
WriteLine
(
"a is greater than 20"
)
;
}
Console
.
WriteLine
(
"The value of a is {0}"
, a
)
;
Console
.
ReadLine
(
)
;
}
}
}
When the code above is compiled and executed, it produces the following result:
a 大于 20
a 的值是 100
if...else if...else statement
A if statement can be followed by an optional else if...else statement, which can be used to test multiple conditions.
When using the if...else if...else statement, note the following:
- An if can be followed by zero or one else, which must come after any else if.
- An if can be followed by zero or more else if statements, which must come before the else.
- Once an else if matches successfully, the other else ifs or the else will not be tested.
Syntax
In C#, if...else if...else statement syntax:
if(boolean_expression 1)
{
/* Execute when boolean expression 1 is true */
}
else if( boolean_expression 2)
{
/* Execute when boolean expression 2 is true */
}
else if( boolean_expression 3)
{
/* Execute when boolean expression 3 is true */
}
else
{
/* execute when none of the above conditions are true */
}
Example
Example
using
System
;
namespace
DecisionMaking
{
class
Program
{
static
void
Main
(
string
[
]
args
)
{
/* Local variable definition */
int
a
=
100
;
/* Check the Boolean condition */
if
(
a
==
10
)
{
/* If the if condition is true, output the following statement */
Console
.
WriteLine
(
"The value of a is 10"
)
;
}
else
if
(
a
==
20
)
{
/* If the else if condition is true, output the following statement */
Console
.
WriteLine
(
"The value of a is 20"
)
;
}
else
if
(
a
==
30
)
{
/* If the else if condition is true, output the following statement */
Console
.
WriteLine
(
"The value of a is 30"
)
;
}
else
{
/* If none of the above conditions is true, output the following statement */
Console
.
WriteLine
(
"No matching value"
)
;
}
Console
.
WriteLine
(
"The exact value of a is {0}"
, a
)
;
Console
.
ReadLine
(
)
;
}
}
}
When the code above is compiled and executed, it produces the following result:
没有匹配的值
a 的准确值是 100
C# Decision Making