Course Content
C# Basics
C# Basics
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:
main
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?