Member-only story

C# Programming Language: Switch Statements

Jesse L
2 min readApr 18, 2022

--

Hi everyone, welcome back. In this tutorial, we will be going over the switch statement. The switch statement can be used to decide which block of code to execute which is good for tasks that include choices and decision making. We will provide an example of how switch statements work along with the break and default keywords which will be needed to work with switch statement. With this introduction out of the way, let’s get into it.

Switch Statement

Let’s look at an example of a switch statement and explain what is happening. Take a look at the example below:

int number = 1;
switch(number)
{
case 1:
Console.WriteLine("One");
break;
case 2:
Console.WriteLine("Two");
break;
}
Output:
One

As we can see, we have created a ‘number’ variable and set it to 1. We then created a switch statement and set it up to check against the ‘number’ variable. The ‘number’ variable is then checked against to each of the cases and if it matches, it will execute the block of code within the case.

In this instance, we set our ‘number’ variable to 1 and the code within ‘case 1’ got executed and we can verify this by printing and checking the output. Below is an example if we changed our ‘number’ variable to 2:

--

--

Jesse L
Jesse L

Written by Jesse L

Hi, I'm a passionate technology enthusiast and lifelong learner. Beyond my technical pursuits, I'm also passionate about sharing my enthusiasm with others.

No responses yet