Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
switch Statement | Control Structures
C# Basics
course content

Course Content

C# Basics

C# Basics

1. Getting Started
2. Dealing with Data Types
3. Control Structures
4. Loops
5. Arrays
6. Methods

switch Statement

The switch statement functions similarly to the conditional statements however it is useful in specific situations.

The syntax for the switch statement is the following:

The resultant of the expression is compared against the cases x, y, z, and so forth. If it matches a case, it executes the code block of that case. If no case is matched then the default code block is executed if it is provided. The expression is most commonly a variable. We write the break keyword after each case's code block to indicate the end of that case.

Following is an example:

cs

main

copy
1234567891011121314151617181920212223242526272829303132333435
using System; namespace ConsoleApp { internal class Program { static void Main(string[] args) { int score = 5; Console.Write("Grade: "); switch(score) { case 1: Console.WriteLine("Fail"); break; case 2: Console.WriteLine("Pass"); break; case 3: Console.WriteLine("Satisfactory"); break; case 4: Console.WriteLine("Good"); break; case 5: Console.WriteLine("Excellent"); break; default: Console.WriteLine("Invalid"); break; } } } }

You can try changing the value of the variable grade to see the change in the output. The value of grade is compared against each case and the relevant output is displayed.

The same code can be written using if-else statements as well; however in this case the switch statement is more efficient and neater. Whenever we have to compare the result of an expression against many possible values, we use the switch statement.

Everything was clear?

Section 3. Chapter 11
We're sorry to hear that something went wrong. What happened?
some-alt