Switch Statement in C# with Examples
Description:
switch statement in c#: in this article, we will discuss a very important condition statement which is a switch case statement in very detail.
switch Statement in C#:
The switch statement in c# Â is used to transfer a string or a numeric value (given by a variable or an expression) to a number of constants.
Syntax of switch statement in c#:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
switch (expression) { case constantA: Instructions); break; case constantB: Instructions); break; default: Instructions); break; } |
The switch statement in c# is evaluated in such a way that the current value of the expression is first determined and is then compared with the constants of the case marks. In the event of a match, the jumps Program execution to the statement that follows the corresponding case label and is carried out from their continued. The break closing the case part ends the switch statement in c#; the application will be continued with the next statement under the switch statement in c#. Matches the value of the expression none of the case constants, program execution jumps to the default label. So here you can handle all cases for which no separate case marks are provided.
There are three points to consider:
- You enter integer constants as simple number literals (3, 423), character literals as usual in single (‘a’, ‘D’) and string literals in double quotes (“red”, “yellow”, “green”).
- The statements for a case block must end with a break. Only if you go to a case Block that does not provide any instructions or can perform a goto jump, the break instruction omitted.
- The specification of the default block is optional.
Note: C # allows not only numeric values ​​but also strings in the switch expression! There is only limited fall-through behavior for this.
Example how to make a simple console menu application in using switch statement in C#:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Demo { class Program { static void Main(string[] args) { int option; Console.WriteLine(); Console.WriteLine("Format Hard Drive <1>"); Console.WriteLine("Turn off screen <2>"); Console.WriteLine("Shut down computer <3>"); Console.WriteLine("Clean Registry <4>"); Console.WriteLine(); Console.Write("Your input:"); option = Convert.ToInt32 (Console.ReadLine ()); switch (option) { case 1: Console.WriteLine ("Formatting hard drive"); break; case 2: Console.WriteLine ("screen will turn off"); break; case 3: Console.WriteLine ("Shutting Down Computer"); break; case 4: Console.WriteLine ("registry is being cleaned"); break; default: Console.WriteLine ("Wrong entry \n"); break; } Console.WriteLine(); Console.ReadKey(); } } } |
Local variables in switch statement in c#:
If several statements are to be executed for a case label, they do not have to be preceded by curly Brackets that can be combined to form an instruction block. The reason for this is that the case marks cannot be compared with the blocks of an if … else statement. The entire switch statement in c# is basically a single block of consecutive instructions. The case brands determine where the block is jumped into, and the break statements determine where the block is left.
As a result, it should be possible to assign a local variable to any case label in the statement block define and then use them in later case brands. Indeed it works! You need to just make sure that the variable has a value beforehand in every case part in which it is used is assigned.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
switch (option) { case 1: int sec = 1; Console.WriteLine ("Process starts in" + sec + "seconds"); break; case 2: sec = 2; Console.WriteLine ("Process starts in" + sec + "seconds"); break; } |
Note: Unlike in C ++, no local variables can be used at the beginning of the switch block, i.e.before the first case mark.
how to use enumeration (enum) types in switch statement in C#:
Since enumeration types also belong to the numeric types, in the switch- Expression also enum variables can be used. The Enum-type constants. The following example demonstrates this using an enumeration for the days of the week.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Demo { enum Day { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday }; class Program { static void Main(string[] args) { DateTime today = DateTime.Now; switch((Day) today.DayOfWeek) { case Day.Monday: case Day.Tuesday: case Day.Wednesday: case Day.Thursday: case Day.Friday: Console.WriteLine ("\n Uff, business day :-("); break; case Day.Saturday: case Day.Sunday: Console.WriteLine ("\n Hurray, weekend :-)"); break; } Console.WriteLine(); Console.ReadKey(); } } } |
Why does Enumeration Day start on Sunday? The reason is that in the switch expression The value of the DateTime property DayOfWeek is queried, which returns the value 0 for Sunday (Monday equals 1, Tuesday equals 2, and so on). So that constants of the day enumeration with the DayOfWeek values ​​match, the Day enumeration started with Sunday. Furthermore, the application uses the fall-through behavior of the switch statement: If several case Marks directly on top of one another (without intervening instructions), each of these case marks serves as an Entry point to the following statement block. With this trick, the application forms all work all weekend days on common instruction blocks. Unlike in C ++ or Java, there is no implicit fall-through in C # for security reasons.
Behavior for case labels that contain their own instructions. Instead, the compiler requires that the Programmer explicitly states his will, either by using a break from the switch statement or jump to another case label with a goto case statement:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
switch (expression) { case 0: ... goto case 2; // explicit fall-through case 1: ... goto case 2; // explicit fall-through case 2: ... break; // leave switch case 3: ... break; // leave switch } |
Note: There is no automatic fall-through behavior for case blocks with Instructions, since these must be terminated with a break or a goto jump.
Example how to find vowel and consonant using switch statement in c#:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Demo { class Program { static void Main(string[] args) { char alph; Console.WriteLine("Enter an alphabet"); alph = Convert.ToChar(Console.ReadLine()); switch (Char.ToLower(alph)) { case 'a': Console.WriteLine("Vowel"); break; case 'e': Console.WriteLine("Vowel"); break; case 'i': Console.WriteLine("Vowel"); break; case 'o': Console.WriteLine("Vowel"); break; case 'u': Console.WriteLine("Vowel"); break; default: Console.WriteLine("consonant "); break; } Console.ReadKey(); } } } |