switch Statement
A switch is like a menu where you say the item number and get exactly that dish. C# compares one value against a list of cases and runs the one that matches.
In this page:
Syntax
switch (value)
{
case value1:
// ...
break;
case value2:
// ...
break;
default:
// no case matched
break;
}
switch Statement
A switch statement compares one value against several case labels and runs the matching block. Each case needs a break (or return) to prevent falling through to the next one. default handles any value that doesn't match a case.
Warning:
Unlike C, C# does not allow implicit fallthrough between non-empty cases — each case must end with
break, return, or goto.Example: switch Statement
using System;
class Program
{
static void Main(string[] args)
{
int day = 3;
string name;
switch (day)
{
case 1:
name = "Monday";
break;
case 2:
name = "Tuesday";
break;
case 3:
name = "Wednesday";
break;
default:
name = "Unknown";
break;
}
Console.WriteLine(name);
}
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Forgetting
breakat the end of a case, which is a compile error in C# because falling through is not allowed. - Not adding a
defaultcase for unexpected values. - Using a non-constant value in a
caselabel, when labels must be constants.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: