Книга: C# 2008 Programmer
if-else Statement
if-else Statement
The most common flow-control statement is the if-else
statement. It evaluates a Boolean expression and uses the result to determine the block of code to execute. Here's an example:
int num = 9;
if (num % 2 == 0) Console.WriteLine("{0} is even", num);
else Console.WriteLine("{0} is odd", num);
In this example, if num
modulus 2 equals to 0, the statement "9 is even" is printed; otherwise (else
), "9 is odd" is printed.
Remember to wrap the Boolean expression in a pair of parentheses when using the if
statement.
If you have multiple statements to execute after an if-else
expression, enclose them in {}
, like this:
int num = 9;
if (num % 2 == 0) {
Console.WriteLine("{0} is even", num);
Console.WriteLine("Print something here...");
}
else {
Console.WriteLine("{0} is odd", num);
Console.WriteLine("Print something here...");
}
Here's another example of an if-else
statement:
int num = 9;
string str = string.Empty;
if (num % 2 == 0) str = "even";
else str = "odd";
You can rewrite these statements using the conditional operator (?:
), like this:
str = (num % 2 == 0) ? "even" : "odd";
Console.WriteLine(str); //---odd---
?:
is also known as the ternary operator.
The conditional operator has the following format:
condition ? first_expression : second_expression;
If condition is true, the first expression is evaluated and becomes the result; if false, the second expression is evaluated and becomes the result.