MorkaLork Development

Interesting stuff I've picked up over the years...

Switch

2009-04-16 17:57:40 | 188 views | switch method loop check

The basics



Switch (select case in VB) is a way to analyse a value and decide what to do with it at once rather than checking it many times(if...else if...else if etc.). The syntax for switch is:

switch(value)
{
case val1:
//do something;
break;
vase val2:
//do something;
break;
}


If we need to check if a bool is true or false, then if...else is sufficient. If we however need to check an int to see what number it is, an if...else statement can get pretty long.

Getting into it



In our example, we will ask the user of our console application to enter a number between 1 and 4. Our program will tell the user if the number is odd or even. We could use if...else here and do if(input == 1){//do something} else if(input == 2) etc etc etc.
That would however be tedious and stupid.
Enter switch.


using System;

namespace TestApp
{
class Program
{
public static void Main(string[] args)
{
Console.Write("Select a number between 1 and 4: ");
string input = Console.ReadLine();

switch (input) {
case "1":
Console.WriteLine("You've entered an odd number");
break;
case "2":
Console.WriteLine("You've entered an even number");
break;
case "3":
Console.WriteLine("You've entered an odd number");
break;
case "4":
Console.WriteLine("You've entered an even number");
break;

default:
Console.WriteLine("You've entered something useless");
break;
}
Console.Read();
}
}
}


This is much easier to read, and we can with great ease enter more cases if we want to.
This can however be even shorter.

Multiple cases:




class Program
{
public static void Main(string[] args)
{
Console.Write("Select a number between 1 and 4: ");
string input = Console.ReadLine();

switch (input) {
case "1": case "3":
Console.WriteLine("You've entered an uneven number");
break;
case "2": case "4":
Console.WriteLine("You've entered an even number");
break;


default:
Console.WriteLine("You've entered something useless");
break;
}
Console.Read();
}
}


As we can see, multiple cases can be written after each other. This can simplify things even more.

Default



In both examples we have used a default at the end of both switches. This means that any other answer than 1 to 4, like 5, 8 or banana, will end up in the line "You've entered something useless". This is similiar to the else keyword in the if...else statement; it handles everything outside the information given to the statement.


Article comments

Feel free to comment this article using a facebook profile.

I'm using facebook accounts for identification since even akismet couldn't handle all the spam I receive every day.