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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Decision Statements ❘ 153<br />

If it’s not Monday and it is Friday, the program sets greeting to "Finally, it's Friday!"<br />

If it’s neither Monday nor Friday, the program sets greeting to "Welcome to" followed by the<br />

current day of the week.<br />

After the series of if-else statements, the program displays the greeting in a message box.<br />

The final else section is optional. If you don’t include it and none of the conditions are true, the<br />

program doesn’t execute any of the corresponding statements.<br />

All the else if statements are also optional. If the code includes only an if statement, either the<br />

program executes the statement that follows or it doesn’t, depending on the value of the condition.<br />

For example, the following code uses a single if statement to display a message box only if it’s<br />

Monday. If it’s any other day of the week, the program does nothing.<br />

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

MessageBox.Show("Sorry, it's Monday.");<br />

The “statement” that the program executes when a condition is true can actually be a block of<br />

statements surrounded by braces. The following shows the syntax.<br />

if (condition1)<br />

{<br />

statement1;<br />

}<br />

else if (condition2)<br />

{<br />

statement2;<br />

}<br />

else if (condition3)<br />

{<br />

statement3;<br />

}<br />

...<br />

else<br />

{<br />

statementElse;<br />

}<br />

You can place as many statements as you like between the braces.<br />

switch Statements<br />

The switch statement lets a program execute one of several pieces of code depending on a single<br />

value. The result is similar to a series of if-else statements that compare a single value to a series<br />

of other values.<br />

The basic syntax is as follows:<br />

switch (value)<br />

{<br />

case expression1:<br />

statements1;<br />

break;<br />

case expression2:<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!