15.02.2015 Views

C# 4 and .NET 4

Create successful ePaper yourself

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

40 ❘ ChaPTer 2 cOre c#<br />

The following code illustrates both how to use goto to simulate fall-through, <strong>and</strong> how messy the resultant<br />

code can get:<br />

// assume country <strong>and</strong> language are of type string<br />

switch(country)<br />

{<br />

case "America":<br />

CallAmericanOnlyMethod();<br />

goto case "Britain";<br />

case "France":<br />

language = "French";<br />

break;<br />

case "Britain":<br />

language = "English";<br />

break;<br />

}<br />

There is one exception to the no-fall-through rule, however, in that you can fall through from one case to<br />

the next if that case is empty. This allows you to treat two or more cases in an identical way (without the<br />

need for goto statements):<br />

switch(country)<br />

{<br />

case "au":<br />

case "uk":<br />

case "us":<br />

language = "English";<br />

break;<br />

case "at":<br />

case "de":<br />

language = "German";<br />

break;<br />

}<br />

One intriguing point about the switch statement in <strong>C#</strong> is that the order of the cases doesn’t matter — you<br />

can even put the default case first! As a result, no two cases can be the same. This includes different<br />

constants that have the same value, so you can’t, for example, do this:<br />

// assume country is of type string<br />

const string engl<strong>and</strong> = "uk";<br />

const string britain = "uk";<br />

switch(country)<br />

{<br />

case engl<strong>and</strong>:<br />

case britain: // This will cause a compilation error.<br />

language = "English";<br />

break;<br />

}<br />

The previous code also shows another way in which the switch statement is different in <strong>C#</strong> compared to<br />

C++: In <strong>C#</strong>, you are allowed to use a string as the variable being tested.<br />

loops<br />

<strong>C#</strong> provides four different loops (for, while, do . . . while, <strong>and</strong> foreach) that allow you to execute a block<br />

of code repeatedly until a certain condition is met.<br />

The for loop<br />

<strong>C#</strong> for loops provide a mechanism for iterating through a loop where you test whether a particular<br />

condition holds before you perform another iteration. The syntax is:<br />

for (initializer; condition; iterator)<br />

statement(s)<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!