Tag Archives: switch

Switch statements in C#

This tutorial explains how to write switch statements in C# language. Switch statements are used to select one from many different blocks of code. A switch statement can take a variable and check if its value matches one of many different specified values. Once the switch statement finds a matching case, it will run the code inside that case and the stop testing all the other cases.

Watch the video below and then scroll down to the sample code to see how switch statements work.

Sample code

using System;

namespace MyCSharpProject
{
  class Program
  {
    static void Main(string[] args)
    {
      int myNumber = 5;
      switch (myNumber) {
        case 1:
          Console.WriteLine("The number is 1");
          break;
        case 2:
          Console.WriteLine("The number is 2");
          break;
        case 3:
          Console.WriteLine("The number is 3");
          break;
        default:
          Console.WriteLine("I don't know this number");
          break;
      }
    }
  }
}

Next tutorial: While loops in C#

Adding toggle buttons to an Android app with Xamarin

This tutorial will show you how to add and use ToggleButton elements for Android apps in Xamarin. ToggleButtons are like on/off switches that only have two possible states and can only be in one state at any one time.

Toggle buttons in an app look like this:

image5

Step 1

To get started, create an Android app solution in Xamarin and open the Main.axml file from the Resources > layout folder. Drag a ToggleButton element on to the screen from the toolbox and give it an Id (eg. @+id/toggleButton1).

image1

The default text for a ToggleButton that is on is “ON” and the default text for a ToggleButton that is off is “OFF”. However, you can change this from the Properties panel.

image2

Step 2

Add a Text (Medium) element to the screen that will display a change in result (eg. ToggleButton switching from off to on). This example TextView is named @+id/resultTextView1.

image3

Step 3

Save the Main.axml file and go to the MainActivity.cs file. Define and set up the ToggleButton and TextView elements in the code and add a CheckedChange method which checks when a change in state is detected. The if statement will check if the ToggleBox is checked and will display the result.

image4
Click the image to see a larger version.

Now go and test your app and this is what it should look like…

image5

Switch statements in C#

We have looked at how to use if statements for conditional programming in C#. However, there is something else we can use if there are many different conditions or cases we want to test. We can use switch statements. Switch statements can contain a number of ‘cases’ and a ‘default’ if none of the specified cases are chosen or met.

Have a look at the sample code below. In this program, the user is asked to enter a number between 1 and 5. Based on the number the user enters, they will be presented with an interesting fact about that number. Each number is a different case and there is also ‘default’ case that will be used if the user does not enter one of those 5 numbers.

Each case also uses a ‘break’ so that if a case is met, then the other cases will not also be checked. In other words, the switch statement will end as soon as a case is met. Here is the sample code:

using System;

namespace MyCSharpApp
{
  class MainClass
  {
    public static void Main (string[] args)
    {
      // Ask the user to enter a number between 1 and 5
      Console.WriteLine ("Enter a number between 1 and 5 for an interesting fact:");
      int number = int.Parse( Console.ReadLine ());

      switch (number) {
      case 1:
        Console.WriteLine ("1 is the number of websites that existed in 1991.");
        break;
      case 2:
        Console.WriteLine ("2 is the only even prime number.");
        break;
      case 3:
        Console.WriteLine ("3 is the number of days you can survive without water (on average).");
        break;
      case 4:
        Console.WriteLine ("4 is the number of miles per second that space junk moves around Earth.");
        break;
      case 5:
        Console.WriteLine ("5 is the length in meters of a Great White Shark.");
        break;
      default:
        Console.WriteLine ("You did not select a valid option.");
        break;
      }

      Console.ReadLine ();
    }
  }
}

Here is an example of what the user will see when they enter the number 4…

switch_cs_example

Note: When copying the code, only copy the actual code you need. The code above uses a namespace that may be different to the name of your project or solution. If you copy all of the code above and replace all of your code with it, then make sure you change the namespace name above to match the one in your project.

Switch statements in PHP

This tutorial explains how to use switch statements in the PHP language. Switch statements can have a number of possible execution paths, unlike if, else and else if statements. Switch statements can be used to test different conditions for a single variable and can be more efficient to write than if, else and else if statements.

If you find you are writing several if, else if, and else statements and you find your code is getting a little messy, then using a switch statement might be the cleaner, neater, and more efficient way to go.

 

A switch statement involves multiple cases that can be tested for a variable as well as a default case if no other conditions (cases) are met. Each case also has a break statement which means if the condition from one case is met, then the switch statement will end and none of the other cases will be tested. To see how to use switch statements in PHP, you can watch the video below or scroll down to see the sample code.

PHP Sample code:

Note how the break; statement is used below. When used, it can stop checking all other cases once a test case evaluates to true. It is optional and if left out, the program will continue to check all other cases and run their code if they evaluate to true, until the switch statement ends.

<?php
 
 $day = 300;
 
 switch($day){
 case 1:
 echo "Monday";
 break;
 
 case 2:
 echo "Tuesday";
 break;
 
 case 3:
 echo "Wednesday";
 break;
 
 case 4:
 echo "Thursday";
 break;
 
 case 5:
 echo "Friday";
 break;
 
 /* 
 Break statement is optional - when it is executed, it will stop
 the switch statement from running
 */
 
 // The default case is also optional.
 
 default:
 echo "Not a weekday";
 break;
 }
 
 
?>

PHP Manual references:

Switch statements

A switch statement is like an IF statement but is neater when working with many conditions. Use the break statement at the end of each case so that the code runs efficiently. If you don’t use break, the program which keep checking through all conditions even if a match has already been found. If none of the conditions are met, then the ‘default’ case will run.

Take a look at the source code below and watch the video here to see switch statements in action.

<!DOCTYPE html>
<html lang="en"
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Switch Statements</title>
 <script type="text/javascript">
 
 // A switch statement is like an IF statement but is neater when working with many conditions.
 // Use the break statement at the end of each case so that the code runs efficiently.
 // If you don't use break, the program which keep checking through all conditions even if a match has
 // already been found. If none of the conditions are met, then the 'default' case will run.
 
 var city="Sydney";
 
 switch(city){
 case "Melbourne":
 document.write("You are from Melbourne");
 break;
 case "Sydney":
 document.write("You are from Sydney");
 break;
 case "Perth":
 document.write("You are from Perth");
 break;
 case "Brisbane":
 document.write("You are from Brisbane");
 break;
 default:
 document.write("You don't live in a city I recognise.");
 }
 
 
 </script>
 
</head>
<body>
 
</body>
</html>

Switch Statements in JavaScript

Switch statements are similar to ‘If’ statements but they are neater when working with many conditions. This video tutorial explains how to use switch statements. View it below or click here to view it on YouTube.

A switch statement is like an IF statement but is neater when working with many conditions.

Make sure you use the break statement at the end of each case so that the code runs efficiently. If you don’t use the break statement, the program will keep checking through all conditions even if a match has already been found. If none of the conditions are met, then the default case will run.

Take a look at the source code below and try using it in your own program.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Switch Statements</title>
 <script type="text/javascript">
 
 // A switch statement is like an IF statement but is neater when working with many conditions.
 // Use the break statement at the end of each case so that the code runs efficiently.
 // If you don't use break, the program which keep checking through all conditions even if a match has
 // already been found. If none of the conditions are met, then the 'default' case will run.
 
 var city="Sydney";
 
 switch(city){
 case "Melbourne":
 document.write("You are from Melbourne");
 break;
 case "Sydney":
 document.write("You are from Sydney");
 break;
 case "Perth":
 document.write("You are from Perth");
 break;
 case "Brisbane":
 document.write("You are from Brisbane");
 break;
 default:
 document.write("You don't live in a city I recognise.");
 }
 
 
 </script>
 
</head>
<body>
 
</body>
</html>

Next tutorial: While loops