Introduction:
This tutorial is on how to use Switch statements in C#.
Switch:
A switch statement allows a single variable or static piece of data to be checked for mulitple conditions, essentially like a long 'else if' statement but a lot more compact and with slightly more flexability.
Case:
To use a switch statement there are a few other keywords we need to learn first, one of which is 'case'.
Case is a possible value of the variable or value being 'switched', this must be of the same data type as the value being switched and must be followed by a colon.
Break is a keyword used to exit the inner-most loop or statement running, in this case it would be the 'case' statement. Break is used to ensure that the case containing the current 'break' keyword/statement does not 'fall through' in to the next case.
Default can be used as a final case just in the event that none of the other cases match the variable or value being 'switched'.
Variable:
Now we are going to write some code. First we will create a string variable which we will use in our switch statement later, we'll name this variable 'switcher' and give it a value of 'Yorkiebar'...
string switcher = "Yorkiebar";
Switch:
Next we create the switch statement, this is the keyword 'switch' followed by the variable/value to be switched in brackets, followed by an enclosed code block...
Cases:
For the cases we write 'case' followed by the value we are testing for, followed by a colon (':'). Under that line, we type what we want to happen, we'll messagebox something, then we type 'break;' to prevent fall throughs to the following case...
case "Yorkiebar":
MessageBox.Show("Hi Yorkiebar!");
break;
case "Josh":
MessageBox.Show("Something's wrong...");
break;
Default:
Finally we can write a default code block for the event that none of the above 'case' statements were correct on the currently being 'switched' variable/value. Default must always go last in a switch statement to avoid errors...
default:
MessageBox.Show("NO!");
break;
Finished!
Here is the full source code...
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace JayPabsSwitchStatements
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string switcher = "Yorkiebar";
switch (switcher)
{
case "Yorkiebar":
MessageBox.Show("Hi Yorkiebar!");
break;
case "Josh":
MessageBox.Show("Something's wrong...");
break;
default:
MessageBox.Show("NO!");
break;
}
}
}
}