Udemy logo

switch case in c#C# is a modern, general purpose , object oriented programming language developed by Microsoft.  C# is also part of the .NET Framework and used mostly for web development and networking related functionality. Being based on C and C++, it is highly structured and fully object oriented. You can learn more about how C# works with the .NET framework in this course.

The switch case programming construct is an important feature of many programming languages including C#. It is used for decision making in several programs – specifically to choose between multiple use cases or options. We walk you through this intermediate tutorial on the switch case construct in C#. This requires some prior understanding of C#. If you’re new to it, you may want to first take this beginners course on C#.

The Switch Case

In a switch statement a variable is compared against a list of values. Each value is termed a case and the variable is checked against each switch case.

The syntax for a switch case statement in C# is as follows:

switch(expression){
case constant-expression1 :
statement(s);
break;
case constant-expression2 :
statement(s);
break;
default :
statement(s);
}

A switch statement has the following rules

To explore more about the Switch Case in C#, you can look up this C# course.

Example 1: Simple Program that uses switch case

Let’s take a simple program to begin with. This program tests the “newvalue” variable against two integer constants: 1 and 6. As it equals 6, we execute the second case. Finally 6 is printed to the console. You could also do this with an if construct, but in situations where there are many such cases to be checked against, switch case is better.

using System;
class NewProgram
{
static void Main()
{
int newvalue = 6;
switch (newvalue)
{
case 1:
Console.WriteLine(1);
break;
case 6:
Console.WriteLine(6);
break;
}
}
}
Output
6

 Example 2: Program that uses int switch

In this program, we’ll take it a step further. We take an input from the user, compare it against our switch cases, and tell the user whether they’ve entered a medium or a low valued integer. We also include a default statement, to catch situations where the integer does not fall into the predefined cases.

class NewProgram
{
static void Main()
{
while (true)
{
System.Console.WriteLine("Type number and press the Enter Key");
try
{
int a = int.Parse(System.Console.ReadLine());
switch (a)
{
case 0:
case 1:
case 2:
{
System.Console.WriteLine("Low Integer");
break;
}
case 3:
case 4:
case 5:
{
System.Console.WriteLine("Medium Integer");
break;
}
default:
{
System.Console.WriteLine("Other Integer");
break;
}
}
}
catch
{
}
}
}
}

 

Example 3: Program that uses char switch

In this example, we show you how to use a character value in a switch case. It’s quite similar to the previous example, except for the subtle differences in dealing with strings and characters instead of integers.

using System;
namespace DecisionMaking
{
class SwitchProgram
{
static void Main(string[] args)
{
char new_grade = 'B';
switch (new_grade)
{
case 'A':
Console.WriteLine("Distinction");
break;
case 'B':
case 'C':
Console.WriteLine("Above Average");
break;
case 'D':
Console.WriteLine("You have passed");
break;
case 'F':
Console.WriteLine("You need to try again");
break;
default:
Console.WriteLine("This is an Invalid grade");
break;
}
Console.WriteLine("Your grade is {0}", new_grade);
Console.ReadLine();
}
}

This program code produces the following result:

Above Average
Your grade is B

If you’d like to learn more about string and character manipulation in C#, check out this C# course.

Example 4: Program that benchmarks ‘switch’

A switch statement is used to optimize certain programs. We mentioned earlier that you could also achieve the same functionality with an if statement. However, if you need to check against a large range of values, a switch case will be much faster. Let’s write a basic benchmark to actually time both methods and see the difference. Switch statement is used in Method1. However Method2 has a series of if statements in place of the switch case programming construct.

 using System;
using System.Diagnostics;
class NewProgram
{
static int Method1(int x)
{
switch (x)
{
case 0:
return 20;
case 1:
return -2;
case 2:
return 40;
default:
return 0;
}
}

static int Method2(int x)
{
if (x == 0) return 20;
if (x == 1) return -2;
if (x == 2) return 40;
return 0;
}

static void Main()
{
Method1(0); Method2(0);
const int max = 100000000;

var s1 = Stopwatch.StartNew();
for (int i = 0; i < max; i++)
{
Method1(0);
Method1(1);
Method1(2);
Method1(3);
}
s1.Stop();
var s2 = Stopwatch.StartNew();
for (int i = 0; i < max; i++)
{
Method2(0);
Method2(1);
Method2(2);
Method2(3);
}
s2.Stop();
Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) /
max).ToString("0.00 ns"));
Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) /
max).ToString("0.00 ns"));
Console.Read();
}
}
Results
9.25 ns   [switch]
9.85 ns   [if]

Note that according to the benchmark, the switch statement version is relatively faster. The time saved could be critical in some applications.

Example 4:Program which uses goto statement in switch

Sometimes you may want to switch to a different location in your code. You can use the goto statement with your switch case. This is used to improve performance and minimize code size in certain situations. This requires a special goto case or goto default.

 using System;
class NewProgram
{
static void Main()
{
Console.WriteLine(GetPrice(1000));
Console.WriteLine(GetPrice(-1));
Console.WriteLine(GetPrice(int.Parse("100")));
}

static int GetPrice(int value)
{
int price = 5;
switch (value)
{
case 1000:
price += 10;
goto case 100;
case 100:
return price * 10;
default:
return price;
}
}
}

Output for this program is as follows.

150
5
50

Example 6: Program that uses loop and switch with break

This program has a for loop containing the switch statement.

using System;
class NewProgram
{
static void Main()
{
for (int x = 0; x < 5; x++)
{
switch (x)
{
case 0:
case 1:
case 2:
{
Console.WriteLine("First three");
break;
}
case 3:
case 4:
{
Console.WriteLine("Last two");
break;
}
}
}
}
}

Here is the output for the above program

First three
First three
First three
Last two
Last two

You can learn more about constructs like the goto statement, loops and breaks in this intermediate C# course.

Hope this tutorial was fun and useful. Do try out these examples for yourself. Experiment with the code and create your own programs. That’ll help you get more comfortable with programming in C#.

Page Last Updated: April 2014

Top courses in C# (programming language)

Ultimate C# Masterclass for 2024
Krystyna Ślusarczyk
4.7 (1,594)
Bestseller
C# in 6 Hours: From Beginner to Pro!
Patrick Videos
4.7 (401)
C#/.NET - 50 Essential Interview Questions (Junior Level)
Krystyna Ślusarczyk
4.8 (465)
Highest Rated
Design Patterns in C# Made Simple
Zoran Horvat
4.5 (431)
Complete C# Unity Game Developer 3D
Ben Tristem, Rick Davidson, GameDev.tv Team, Gary Pettie
4.7 (40,764)
Bestseller
Complete C# Masterclass
Denis Panjuta, Tutorials.eu by Denis Panjuta
4.6 (28,043)
Design Patterns in C# and .NET
Dmitri Nesteruk
4.4 (11,468)
Bestseller
C# 10 | Ultimate Guide - Beginner to Advanced | Master class
Web University by Harsha Vardhan
4.6 (3,213)

More C# (programming language) Courses

C# (programming language) students also learn

Empower your team. Lead the industry.

Get a subscription to a library of online courses and digital learning tools for your organization with Udemy Business.

Request a demo