Intro to C#: Switch

Redmond Chan
2 min readDec 25, 2019

--

If you are new to programming, I’d suggest reading my previous post first because it teaches you some basics that I’d be using here.

I’ll be talking about switch statements today. A switch statement is like an if else statement. The argument you pass into the switch statement gets tested against all cases. Once the case is true, it’ll execute the code below.

A switch statement takes in an argument, in the example above, it takes in the argument of num. The value after “case”, is the value that the argument will be compared to.

Case 1, tests if num has the value of 1. Case 2, tests if num has the value of 2. Case 3, tests if num has the value of 3. Since num has the value of 3, case 3 is true and it’ll execute line 17.

If num had the value of 1, it would execute line 11 instead.

In this example, I will ask you to pick a color and it’ll set it to variable color and then get tested in the switch statement. If you entered in “red”, it’ll execute line 19.

Notice the default case in line 21. If none of the cases evaluate to true, then it’ll execute line 22. If you entered in “blue”, I don’t have a case where it checks for “blue” so none of the cases will evaluate to true so it’ll print out “You did not pick from the colors provided.”.

Here are some reasons that your switch statement will give you an error that I came across while playing around with the switch statement:

You need to include the break in each case or else it’ll give you an error.

If the argument data type does not match the data type of the cases, there’ll be an error.

Here are the examples I used today and I included examples for the errors I came across. Feel free to uncomment it and run the code to become more familiar C#!

https://repl.it/@redmondchan/CSharp-Switch

--

--