Switch Statements in C#



C# switch statement

The switch statement is used when we have multiple condition but only one condition true and only that code will be executed.
In other word we can say execute one of multiple blocks of code to be executed.

The switch statement works same as if-else if-else statement.

C# switch statement

switch (a)
{
case statement1:
if a=statement1 then code to be executed;
break;
case statement2:
if a=statement2 then code to be executed;
break;
case statement3:
if a=statement3 then code to be executed;
break;
…….
default:
if “a” is not matches with any statement then code to be executed.
}


Adding switch Statement in C# .Net

Open visual studio and create new website with c#. Open a web form code part and right click anywhere between brackets of the page load portion. On the right click menu select Insert Snippet and click on it as shows in below figure.

meeraacademy.com
C# Switch Statement

After click on Insert Snippet option from menu, you will see a list of items, Now double click on Visual C#.

meeraacademy.com
C# Switch Statement

After double click on Visual C# option from items, you have list of snippets, Now double click on switch.

meeraacademy.com
C# Switch Statement

After double click on switch option from list of snippets, you will have code of switch statement on your web page.

C# Switch Statement

Example of switch statement in C#.

int a = 7;

switch (a)
{
case 15:
Response.Write("Value of a is 15");
break;
case 10:
Response.Write("Value of a is 10");
break;
case 7:
Response.Write("Value of a is 7");
break;
default:
Response.Write("Invalid Value");
break;
}

The output is:
Value of a is 7

Related ASP.Net Topics :

If Conditional Statement in C#.Net
If-Else If-Else Statement in C#.Net


Subscribe us

If you liked this c#.net post, then please subscribe to our YouTube Channel for more c#.net video tutorials.

We hope that this asp.net c# tutorial helped you to understand Switch Statement.


Next asp.net tutorial we will learn about C# Loop Types.


Leave a Reply

Your email address will not be published. Required fields are marked *