03.11.2016 Views

Beginning ASP.NET 4.5 in CSharp and VB Opsylum

Create successful ePaper yourself

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

Statements x 169<br />

<strong>VB</strong>.<strong>NET</strong><br />

Dim today As DateTime = DateTime.Now<br />

Dim discountPercentage As Double = 0<br />

Select Case today.DayOfWeek<br />

Case DayOfWeek.Monday<br />

discountPercentage = 40<br />

Case DayOfWeek.Tuesday<br />

discountPercentage = 30<br />

Case DayOfWeek.Wednesday<br />

discountPercentage = 20<br />

Case DayOfWeek.Thursday<br />

discountPercentage = 10<br />

Case Else<br />

discountPercentage = 0<br />

End Select<br />

C#<br />

DateTime today = DateTime.Now;<br />

double discountPercentage = 0;<br />

switch (today.DayOfWeek)<br />

{<br />

case DayOfWeek.Monday:<br />

discountPercentage = 40;<br />

break;<br />

case DayOfWeek.Tuesday:<br />

discountPercentage = 30;<br />

break;<br />

case DayOfWeek.Wednesday:<br />

discountPercentage = 20;<br />

break;<br />

case DayOfWeek.Thursday:<br />

discountPercentage = 10;<br />

break;<br />

default:<br />

discountPercentage = 0;<br />

break;<br />

}<br />

For each day where the discount is applicable (Monday through Thursday) there is a Case block.<br />

The differences between <strong>VB</strong>.<strong>NET</strong> <strong>and</strong> C# syntax are quite small: C# uses a lowercase c for case<br />

<strong>and</strong> requires a colon after each case label. Additionally, you need to exit each block with a break<br />

statement. At run time, the condition (today.DayOfWeek) is evaluated <strong>and</strong> the correct block is executed.<br />

It’s important to underst<strong>and</strong> that only the relevant block is executed, <strong>and</strong> noth<strong>in</strong>g else. When<br />

no valid block is found (the code is executed on a day between Friday <strong>and</strong> Sunday), the code <strong>in</strong> the<br />

Case Else or default block fires. You’re not required to write a Case Else or default block,<br />

although it’s recommended to do so because it makes your code more explicit <strong>and</strong> easier to read.<br />

The preced<strong>in</strong>g examples could have left it out, because discountPercentage already gets a default<br />

value of 0 at the top of the code block.<br />

To get a feel for the statements you have seen so far, the follow<strong>in</strong>g Try It Out exercise shows you<br />

how to use them <strong>in</strong> a small demo application.

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

Saved successfully!

Ooh no, something went wrong!