03.01.2015 Views

C# 5.0 Programmer's Reference

Visual Studio 2013 C# 5.0 Programmer's Reference

Visual Studio 2013 C# 5.0 Programmer's Reference

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

152 ❘ CHAPTER 7 Program Control Statements<br />

if-else Statements<br />

The if-else statement has the following syntax:<br />

if (condition1) statement1;<br />

else if (condition2) statement2;<br />

else if (condition3) statement3;<br />

...<br />

else statementElse;<br />

The conditions are logical expressions that evaluate to either true or false. The statements are the<br />

statements that should be executed if the corresponding condition is true.<br />

The program evaluates each of the conditions until it finds one that is true. It then evaluates the<br />

corresponding statement and skips all the rest of the series of else and if statements.<br />

Short Circuiting Ifs<br />

Because the program skips any remaining else and if statements, a series of if-else<br />

statements provides short-circuit evaluation similar to the behavior given by the ||<br />

operator. In particular, the program doesn’t evaluate the conditions used by those<br />

statements. Normally, that’s okay and saves the program some time, but it can be a<br />

problem if those conditions invoke methods with side effects.<br />

For example, suppose a condition calls the EmployeeExists method. If that<br />

method opens an employee database and leaves it open, that is a side effect. If you<br />

don’t know whether that condition will be checked, after the series of if-else<br />

statements finishes, you won’t know whether the database has been opened.<br />

The best way to avoid this issue is to not write methods that have unexpected side<br />

effects. For more on side effects, see the discussion of the && and || operators in the<br />

section “Logical Operators” in Chapter 5.<br />

If none of the conditions are true, the program executes statementElse.<br />

For example, consider the following code snippet.<br />

string greeting = "";<br />

if (DateTime.Now.DayOfWeek == DayOfWeek.Monday)<br />

greeting = "Sorry, it's Monday.";<br />

else if (DateTime.Now.DayOfWeek == DayOfWeek.Friday)<br />

greeting = "Finally, it's Friday!";<br />

else<br />

greeting = "Welcome to " + DateTime.Now.DayOfWeek.ToString();<br />

MessageBox.Show(greeting);<br />

The code starts by creating the string variable greeting and initializing it to a blank string. It then<br />

begins a series of if-else statements.<br />

If it’s Monday, the program sets greeting to "Sorry, it's Monday."<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!