Later Today: ASP.NET Tutorial 2: Introduction to C#

ASP.NET Tutorial 5: Conditionals 2 ( switch constructs )

This article explains the use of switch constructs. Switch constructs are a conditional, like if/else constructs discussed in the previous ASP.NET Tutorial 4. In all honesty, you won’t use switch blocks nearly as often as you will use if… but there are times when they just plain make more sense.

> Introduction to Switch

Introduces the use of switch constructs, and suggests some useful scenarios.

A switch block compares a single variable or value to any number of other values, and when it finds a match, it executes some code. What really makes switch blocks handy is that after it finds a match, it will keep checking conditions until you tell it to stop (by using the break keyword).

switch blocks are structured like this:

(C#) Pseudocode Structure Example:
switch ([variable])
{
    case [value to check variable against]:
        [code here]
        break;
    case [value to check variable against]:
        [code here]
        break;
    default:
        [code here]
        break;
}

The way C# reads this is:

  1. switch: Get the value in parenthesis for comparison.
  2. case: If our value is equal to this value, run the code that follows the colon. If our value is NOT equal to this value, skip ahead to the next case statement.
  3. break: Immediately exit the switch block (will not check any more cases).
  4. default: Works just like case, but will always run unless a break keyword exits the switch block before default is reached. In other words, default is what happens when you don't explicitly break out of the switch beforehand.

For example, let's assume that we have a string variable storing a username, and we want to check that variable against two possibilities so we can display a special message to those specific users. If the variable doesn't match either of those two possibilities, we'll use a boring generic message instead. Such code might look like this...

(C#) Switch Construct Practical Example:
string strMessage;
string strUserName = "BobMarley";

switch(strUserName)
{
    case "BobMarley":
    	strMessage = "I be jammin' wit you!";
    	break;
    case "MrHankey":
    	strMessage = "Well, howdy ho!";
        break;
    default:
    	strMessage = "Welcome back!";
        break;
}

And that's literally all there is to it.

No Comments

Post a Comment

You must be logged in to post a comment.

RSS Twitter LinkedIn Facebook
Doing neato things with JavaScript, please wait...